Reputation: 205
public frame() {
JFrame frame = new JFrame("Test");
frame.setSize(400,300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
int i = 4;
int j = 4;
JPanel[][] panelHolder = new JPanel[i][j];
for (int a = 0; a < i; a++) {
for (int b = 0; b < j; b++) {
panelHolder[a][b] = new JPanel();
add(panelHolder[a][b]);
}
}
panelHolder[3][2].setForeground(Color.BLUE);
JButton enter = new JButton("Enter");
panelHolder[0][0].add(enter);
frame.setVisible(true);
When I try to add a component to a panel or set the color nothing changes, I used this code from elsewhere but I wrote it down the other day and can't find it again, but the loops are adding the JPanels to the frame right? so why can't I add to the JPanels?
Upvotes: 1
Views: 2756
Reputation: 4122
The problem is that you have an object in your constructor with the same name as your class, but when calling setVisible()
, you are not using it. You can solve that by making your class extend JFrame
, and then using this constructor:
public frame() {
setSize(400, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
int i = 4;
int j = 4;
JPanel[][] panelHolder = new JPanel[i][j];
for (int a = 0; a < i; a++) {
for (int b = 0; b < j; b++) {
panelHolder[a][b] = new JPanel();
add(panelHolder[a][b]);
}
}
panelHolder[3][2].setForeground(Color.BLUE);
JButton enter = new JButton("Enter");
panelHolder[0][0].add(enter);
setVisible(true);
}
Upvotes: 6