I am trying to make a GUI maze game, where as the computer tries to solve the maze, it changes the colors of the point in the maze it is on. The maze is made up of a JFrame with a JPanel (GridLayout). In the grid is the JPanels that I need to change their colors. I'm not sure how to even access them after I create them.
My code:
public Maze(int length) {
JFrame frame = new JFrame();
JPanel panel = new JPanel(new GridLayout(length, length, 5,5));
panel.setPreferredSize(new Dimension(500, 500));
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
JPanel p2 = new JPanel();
p2.setBackground(Color.red);
panel.add(p2);
}
}
frame.setDefaultCloseOperation(3);
frame.setTitle("Maze Game");
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
Is there a way to change the color of p2
in a different method? Or is there a better way to do it?