Reputation: 1957
I am working with Swing and I created a JFrame in which I put 9 buttons. But I need to access quickly to these buttons, so I would like to create a table of all my JButtons, where I'll be able to access rapidly the buttons. But I dont find the syntax to declare it...
Can you help me ?
Upvotes: 1
Views: 516
Reputation: 159754
The simplest way would be to use a GridLayout
and add all your buttons to that container.
public class GridDemo {
public void showUI() {
JFrame frame = new JFrame("Grid \"Table\" Demo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLayout(new GridLayout(0, 3));
for (int i=0; i < 9; i++) {
frame.add(new JButton("Button " + (i + 1)));
}
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
GridDemo gridDemo = new GridDemo();
gridDemo.showUI();
}
});
}
}
Upvotes: 1
Reputation: 3788
You can use MiG Layout to easily place all of your items in your JFrame (not only to place your buttons). It makes the placement of your items much easier with less code.
Upvotes: 2