Joe Balin Joe Balin - 4 days ago 5
Java Question

Positioning JLabel in Corner

I'm pretty nooby at layouts... for my application I want to put a panel in the bottom-left corner, with padding, but I'm not sure which layout to use.

I tried using a BorderLayout coupled with horizontal alignment in order to position the panel in the corner, but it did not produce the expected result. My code is as follows:

final JLabel label = new JLabel();
label.setBorder(new EmptyBorder(20, 20, 20, 20));
label.setHorizontalAlignment(JLabel.LEFT);
label.setPreferredSize(new Dimension(100,100));
label.setBackground(Color.WHITE);
label.setOpaque(true);
add(label, BorderLayout.SOUTH);


(the outer class extends JFrame)

The image below details what I want, and what I have.
what I want vs what I have

Any tips to achieve this layout? It seems rather simple, but again, I'm noob at layouts :(

Answer

You can use a SpringLayout.

It's tricky, but it'll do the trick.

SpringLayout springLayout = new SpringLayout();
Container cont = getContentPane();
cont.setLayout(springLayout);

JLabel label = new JLabel("New label");
springLayout.putConstraint(SpringLayout.WEST, label, 20, SpringLayout.WEST, cont);
springLayout.putConstraint(SpringLayout.SOUTH, label, -10, SpringLayout.SOUTH, cont);
cont.add(lblNewLabel);

Spring Layout allows you to set the distance between the sides of components and the frame, and eventually set it's location in a dynamic way (the location will remain relative to the frame when you resize)

this is the output:

output

Comments