Chaz Chaz - 1 month ago 6
Java Question

Array of JPanels on a JFrame

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?

Answer

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);
}