Reputation: 571
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
...
Upvotes: 0
Views: 169
Reputation: 4047
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"));
}
}
Try this code sample
Upvotes: 1
Reputation: 8657
You need to use a GridLayout
layout manager.
For Example:
buttonPane.setLayout(new GridLayout(rows, cols));
Read more a bout GridLayout.
Upvotes: 3