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

2

6

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?

Psychotomimetic answered 20/12, 2011 at 17:5 Comment(0)
N
4

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"));
Neurosurgery answered 20/12, 2011 at 17:19 Comment(0)
K
2

If you don't mind vertically stretched buttons, why not to try:

import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JFrame;

public class JFrame1 {
public static void main(String[] args) {
        JFrame frame = new JFrame();
        JButton btn1 = new JButton("Btn1");
        JButton btn2 = new JButton("Btn2");
        frame.setLayout(new BorderLayout());
        frame.setSize(500, 400);
        frame.add(btn1, BorderLayout.WEST);
        frame.add(btn2, BorderLayout.EAST);
        frame.show();
    }
}

enter image description here

Kane answered 20/12, 2011 at 17:24 Comment(1)
Also consider a nested layout in EAST and WEST, FlowLayout.Cammack

© 2022 - 2024 — McMap. All rights reserved.