I want to make a GUI, and for it I need to use absolute positioning, since I want each element to have a precise position within my frame.

I am making each element that makes up the frame by extending JPanels, so I'm building each block within the window separate from the frame itself.

My problem is, that when I'm creating a button or anything else, and I use the setBounds method on the elements it does position them where i want to, but in respect to the frame itself, not the JPanel which contains them.

What I need is for setBounds, to set the bounds according to the JPanel and not the main JFrame. It goes something like this:

JFrame x = new JFrame("Test");

JButton a = new JButton("abc");
JButton b = new JButton("def");

a.setBounds(2, 2, 20, 20);

b.setBounds(3, 3, 20, 20);

JPanel y = new JPanel();
JPanel z = new JPanel();

y.setLayout(null); z.setLayout(null);



If i try the above as it is, I will get the buttons stacked on another. I need some way so that button "b" appears 3 pixels to the right of the "y" panel and not 3 pixels away from the JFrame border.

Thank you

5 Years
Discussion Span
Last Post by geekman89

Have you tried getting the location of the panel and then adjusting your components positions by considering the panel's location.


Thank you for your suggestion. I have made a method for each JPanel that sets the positions. It works!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.