将按钮与盒子组件对齐

时间:2013-10-14 11:26:25

标签: java swing alignment boxlayout

所以我想创建这样的东西:

enter image description here

最后我正在取得一些进展,但我很困惑为什么我的按钮没有与中心对齐,以及它为什么不在它们之间产生间隙。

这是我的代码:

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);

这就是它所创造的:

enter image description here

我做错了什么?

编辑:修复了按钮之间差距的问题。我意识到我没有把它添加到画布上。但仍然与对齐问题相混淆。

1 个答案:

答案 0 :(得分:4)

BoxLayout不是您应该用于该任务的最佳布局。我建议将BorderLayoutFlowLayout结合使用。所以,像这样:

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);