Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aligning JComponents to left- and right-hand sides of a JPanel

I have a JPanel that contains two JComponents, say two JButtons, btnLeft and btnRight. I want these two buttons aligned horizontally and I want btnLeft to be on the left side of the JPanel and btnRight to be on the right side of the JPanel with whatever space is left over in between.

I know I can do this with a BoxLayout by adding a horizontal strut in which I have to specify the amount of space in between, but there must be a simpler way without having to specify what the left-over space in between is.

How do I do this?

like image 931
Paul Reiners Avatar asked Dec 20 '11 17:12

Paul Reiners


People also ask

How do I align a JPanel to the left?

//To align it to the left p. add(b, BorderLayout. WEST); //To align it to the right p. add(b, BorderLayout.

How do I change the layout of a JPanel?

You can set a panel's layout manager using the JPanel constructor. For example: JPanel panel = new JPanel(new BorderLayout()); After a container has been created, you can set its layout manager using the setLayout method.

How do I center a JPanel screen?

If you want to let the frame appear at the center of your screen, you can set the location by: frame. setLocationRelativeTo(null); Note that you would want to invoke the above after you set the size (or pack() ) your frame.

How do you add a border to a JPanel?

createLineBorder() − To create a line border. JPanel. setBorder(border) − To set the desired border to the JPanel.


1 Answers

Sounds like horizontalGlue is what you are looking for:

    JComponent comp = new JPanel();
    comp.setLayout(new BoxLayout(comp, BoxLayout.LINE_AXIS));
    comp.add(new JLabel("left"));
    comp.add(Box.createHorizontalGlue());
    comp.add(new JLabel("right"));
like image 124
kleopatra Avatar answered Sep 23 '22 06:09

kleopatra