Search code examples
javaswingalignmentboxlayout

Aligning buttons with box component


So I want to create something like this:

enter image description here

Finally I'm making some progress, but I'm confused as to why my buttons aren't aligning to the centre and as to why it isn't creating a gap between them.

Here's my code:

canvas.setLayout(new BoxLayout(canvas, BoxLayout.X_AXIS));

//buttons
final JButton btn1 = new JButton(play);
btn1.setBorder(BorderFactory.createEmptyBorder());
btn1.setContentAreaFilled(false);
btn1.setAlignmentX(Component.CENTER_ALIGNMENT);
btn1.getModel().addChangeListener(new ChangeListener() {
    @Override
    public void stateChanged(ChangeEvent e) {
        ButtonModel model = (ButtonModel) e.getSource();
        if (model.isRollover())
            btn1.setRolloverIcon(playro);
    }
});
final JButton btn2 = new JButton(instructions);
btn2.setBorder(BorderFactory.createEmptyBorder());
btn2.setContentAreaFilled(false);
btn2.setAlignmentX(Component.CENTER_ALIGNMENT);
btn2.getModel().addChangeListener(new ChangeListener() {
    @Override
    public void stateChanged(ChangeEvent e) {
        ButtonModel model = (ButtonModel) e.getSource();
        if (model.isRollover())
            btn2.setRolloverIcon(instructionsro);
    }
});     

canvas.add(btn1);
canvas.add(Box.createHorizontalStrut(10));
canvas.add(btn2);

This is what it creates:

enter image description here

What am I doing wrong?

EDIT: Fixed the issue with the gap between the buttons. I realised I wasn't adding it to the canvas. Still confused with the alignment issue though.


Solution

  • BoxLayout is not the best layout you should use for that task. I would recommend BorderLayout in conjunction with FlowLayout. So, something like this:

    canvas.setLayout(new BorderLayout());
    
    JPanel bottomPanel = new JPanel(); // Panel where you can
    // place those buttons (by default,
    // FlowLayout has been set on it)
    bottomPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 30, 0));
    canvas.add(bottomPanel, BorderLayout.SOUTH);
    bottomPanel.add(btn1);
    bottomPanel.add(btn2);