Search code examples
javajbuttonjdialog

JDialog - Add and arrange buttons


I have this code where I add 9 buttons, but I want them to appear in 3 different lanes (3 buttons for each row) but I do not know how to, any suggestions?

...

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
...

Solution

  • You need to use a GridLayout layout manager.

    For Example:

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

    Read more a bout GridLayout.