有没有办法让 JButtons 换行,JOptionPane

Is there a way to get JButtons on a new line, JOptionPane

我正在 java 中制作一个基本的音板,我想要它以便每 2 个按钮都在不同的行上,例如:

(button) (button)
(button) (button)

这是我目前的代码

JPanel p = new JPanel();
JButton one = new JButton(sound1);
JButton two = new JButton(sound2);
JButton three = new JButton(sound3);
JButton four = new JButton(sound4);
JButton five = new JButton(sound5);

p.add(one);
p.add(two);
p.add(three);
p.add(four);
p.add(five);

int n = JOptionPane.showConfirmDialog(null, p, "Test", JOptionPane.OK_CANCEL_OPTION, -1);

最简单的方法是什么?如果我必须切换到 JFrame,请告诉我我不会介意这是唯一的选择。

您可以使用 GridLayout,它在 table 中显示组件。如下所示,3 是行数,2 是列数。

    p.setLayout(new GridLayout(3, 2));

    p.add(one);
    p.add(two);
    p.add(three);
    p.add(four);
    p.add(five);

只需在 JPanel:

中使用 GridLayout
JPanel p = new JPanel(new GridLayout(0, 2));

第一个参数是行数,第二个参数是列数。如果您将行数指定为 0,那么您就是在告诉布局管理器您只想拥有两列,但不知道需要多少行 - 行将动态创建。