2

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?

Zong
  • 6,160
  • 5
  • 32
  • 46
YazanLpizra
  • 520
  • 1
  • 11
  • 32

1 Answers1

6

If your have the referee of JFrame then you can do it in this way.

    int count = 0;
    for (Component comp : frame.getContentPane().getComponents()) {
        System.out.println(comp.getBackground());
        if (count == 6) {
            comp.setBackground(Color.GREEN);
        }
        count++;
    }

Here 6 represent 2nd row and 3rd column as in the same order the JPanel are added in JFrame.

enter image description here


Complete Sample Code [EDITED]

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;

public class Maze {
    private JFrame frame = null;

    public Maze(int length) {

        frame = new JFrame();

        JPanel panel = new JPanel(new GridLayout(length, length, 5, 5)) {
            private static final long serialVersionUID = 1L;

            @Override
            public Dimension getPreferredSize() {
                return 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(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("Maze Game");
        frame.setContentPane(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public void setPanelColor(int index) {
        frame.getContentPane().getComponents()[index].setBackground(Color.GREEN);
    }

    public static void main(String[] a) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception ex) {
                }
                Maze maze = new Maze(4);
                maze.setPanelColor(6);
            }
        });
    }
}

Edits:

  1. EventQueue.invokeLater()

    All GUI related things in java should always go through a single thread. The thread is our legendary AWT-EventQueue . Hence all GUI related actions should necessarily go through the AWT Event thread. If not so you may end up in a deadlock.

    Read more Should we use EventQueue.invokeLater for any GUI update in a Java desktop application?

  2. UIManager.setLookAndFeel()

    UIManager manages the current look and feel, the set of available look and feels.

    Read more How to Set the Look and Feel

  3. JComponent#getPreferredSize()

    Read more Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
  • But can I do this in a separate method? or would I have to have the class extend JFrame? – YazanLpizra Mar 16 '14 at 14:25
  • 1
    Do you have the reference of `JFrame`? – Braj Mar 16 '14 at 14:26
  • Im not sure I know what you mean. What exactly is a reference? – YazanLpizra Mar 16 '14 at 14:27
  • 1
    You can access it by creating an instance or static member in your class having multiple methods. – Braj Mar 16 '14 at 14:27
  • 1
    You should have the main Panel as instance variable of maze. not local variables, then you can refer. – nachokk Mar 16 '14 at 14:28
  • Ok, so instead of declaring the JFrame in the constructor, declaring it outside will allow any other method to access it. Would it also work if I made the class extend JFrame? – YazanLpizra Mar 16 '14 at 14:32
  • 1
    Yes, You are right and you can do it also by extending `JFrame` and access it by using `this` – Braj Mar 16 '14 at 14:33
  • 3
    Extending JFrame is really a bad idea cause you are not adding any functionality to the JFrame, preferring composition over inheritance, and think that could be better to have as instance variable the main JPanel rather than the jframe. – nachokk Mar 16 '14 at 14:35
  • @nachokk I strongly agree with you. **I always respect Design Patterns** – Braj Mar 16 '14 at 14:38