JDialog - 添加和排列按钮

时间:2014-04-14 09:37:08

标签: java jbutton jdialog

我有这个代码,我添加了9个按钮,但我希​​望它们出现在3个不同的通道中(每行3个按钮)但我不知道如何,有任何建议吗?

...

JPanel buttonPane = new JPanel();

//JButton1
JButton jButton1 = new JButton("OK");
jButton1.setText("Package 1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
    @Override
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton1ActionPerformed(evt);
    }
});
buttonPane.add(jButton1);

//JButton2
JButton jButton2 = new JButton("OK");
jButton2.setText("Package 2");
jButton2.addActionListener(new java.awt.event.ActionListener() {
    @Override
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton2ActionPerformed(evt);
    }
});
buttonPane.add(jButton2);

//JButton3
...

2 个答案:

答案 0 :(得分:3)

您需要使用GridLayout布局管理器。

例如:

buttonPane.setLayout(new GridLayout(rows, cols));

了解更多回合GridLayout

答案 1 :(得分:1)

 public class ButtonGrid 
 {
     JPanel buttonPane = new JPanel();
     public ButtonGrid() 
     {
         buttonPane .setLayout(new GridLayout(3,3));
         buttonPane.add(new Button("1"));
         buttonPane.add(new Button("2"));
         buttonPane.add(new Button("3"));
         buttonPane.add(new Button("4"));
         buttonPane.add(new Button("5"));
         buttonPane.add(new Button("6"));
         buttonPane.add(new Button("7"));
         buttonPane.add(new Button("8"));
         buttonPane.add(new Button("9"));
     }
 }

试试此代码示例