Hello
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);

y.add(a);
z.add(b);

x.add(y);
x.add(z);

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

Recommended Answers

All 2 Replies

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!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.