I have one JFrame that is set to a GridLayout of size NxN. N is given by the user as a command line at the start of the program. JButtons in an NxN pattern are added to the
Does each JButton need its own JPanel to use GridLayout?
No. Add and setLayout on JFrame don't do what they appear to. JFrame is Top-Level Containers and it is better to organise your content in JPanels.
You should organize your panels in that form:
----JPanel----------------------------|
| ---LeftPanel--- ---ButtonsPanel--- |
| | | | | |
| | | | | |
| | | | GridLayout(N,N)| |
| | | | | |
| | | | | |
| --------------- ------------------ |
---------------------------------------
Then add JPanel to the JFrame. Also put panels in seperate classes:
class BPanel extends JPanel {
public BPanel() {
GridLayout layout = new GridLayout(N,N, hgap, vgap);
setLayout(layout);
for (int row = 0; row < N; row++){
for (int col = 0; col < N; col++){
JButton b = new JButton ("("+row+","+col+")");
add(b).setLocation(row, col);
b.addActionListener(new ButtonEvent(b, system, row, col));
}
}
}
}
class LeftPanel extends JPanel {
....
}
class MainFrame extends JFrame {
public MainFrame() {
JPanel p = new JPanel();
p.add(new LeftPanel());
p.add(newButtonsPanel());
add(p);
}
}