在JFrame中使用BoxLayout

时间:2016-04-12 17:43:12

标签: java swing jframe layout-manager boxlayout

我正在尝试使用JFrame和BoxLayout来实现类似于所示的GUI,但我不确定如何将我的停止和播放按钮居中。有什么建议吗?

enter image description here

这是我的代码:

JFrame frame = new JFrame();

    Box box = Box.createHorizontalBox();
    box = Box.createHorizontalBox();
    box.add(new JButton("Play"));
    box.add(new JButton("Stop"));
    box.add(Box.createHorizontalGlue());
    frame.add(box, BorderLayout.SOUTH);

    frame.setSize(500, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setVisible(true); 

我还没有在文本框和加载按钮中编码,因为我还没有能够找到居中。

1 个答案:

答案 0 :(得分:2)

为按钮创建单独的面板。使用水平胶水,您可以将按钮居中。

JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));

buttonPanel.add(Box.createHorizontalGlue());

buttonPanel.add(new JButton("Play"));
buttonPanel.add(new JButton("Stop"));

buttonPanel.add(Box.createHorizontalGlue());

frame.add(buttonPanel, BorderLayout.SOUTH);

您也可以轻松地使用FlowLayout

JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));

buttonPanel.add(new JButton("Play"));
buttonPanel.add(new JButton("Stop"));

frame.add(buttonPanel, BorderLayout.SOUTH);