2

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

在此处输入图像描述

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

这是我的代码:

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

这是它创建的:

在此处输入图像描述

我究竟做错了什么?

编辑:修复了按钮之间的间隙问题。我意识到我没有将它添加到画布上。尽管如此,仍然对对齐问题感到困惑。

4

1 回答 1

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);
于 2013-10-14T11:50:17.657 回答