Search code examples
javaswingjbuttonjtextfieldboxlayout

Centering JButton in BoxLayout, JTextField padding


I've created simple JDialog to gain initial data for my application. Elements (JLabel, JTextField and JButton) are arranged by BoxLayout inside the BorderLayout. (Code at the end). So far it looks like this:

Current arrangement

I have two problems:

  1. I would like to center JButton in it's row. I tried startBtn.setAlignmentX(Component.CENTER_ALIGNMENT);, but it doesn't work properly, mess appears.

  2. I want to add some left/right padding to TextField. First solution from this topic works fine, but other elements are moved right left padding value.

Can anybody give a hint how to place it? I'm new to Java and have no idea.

Here's code of my InitDialog class:

public class InitDialog extends JDialog {

    JTextField dataTF;
    JButton startBtn;

    public InitDialog(JFrame owner) {

        super(owner, "Rozpocznij test", Dialog.ModalityType.DOCUMENT_MODAL);
        initUI();

    }

    public final void initUI() {

        System.out.println("InitDialog::initUI");

        JPanel outer = new JPanel(new BorderLayout());
        JPanel inner = new JPanel();

        outer.setBorder(new EmptyBorder(new Insets(20, 20, 20, 20)));

        JLabel msg = new JLabel("<html>Podaj ilości liczb w zestawach testowych<br />(przedzielone średnikiem):");
        inner.add(msg);
        inner.add(Box.createVerticalStrut(15));

        dataTF = new JTextField();
        dataTF.setBorder(null);
        dataTF.setText("50; 100; 200");
        inner.add(dataTF);
        inner.add(Box.createVerticalStrut(15));

        startBtn = new JButton("Rozpocznij test");
        inner.add(startBtn);

        inner.setLayout(new BoxLayout(inner, BoxLayout.Y_AXIS));
        outer.add(inner);
        add(outer);

        setSize(300, 180);

        //setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        addWindowListener(new WindowAdapter() {
            @Override public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        setResizable(false);
        setLocationRelativeTo(getRootPane());

    }

}

Solution

  • BoxLayout alignment is not what you think it is.

    To get what you want this is the line you need

    msg.setAlignmentX(Component.CENTER_ALIGNMENT);