user2880113
user2880113

Reputation: 355

Java - Painting

Hello im trying to create a grid in java and paint each cell but I dont kown what im doing wrong. Each cell is a JPanel and I add each cell to the to the mazePanel. After that the mazePanel is added to the frame. But only get the result shown in the next image:

enter image description here

public void printFrame() {

    JFrame frame;
    JPanel mazePanel = new JPanel();
    frame = new JFrame("The Maze");
    frame.setSize(600, 600);
    mazePanel.setLayout(new GridLayout(2, 2));

    mazePanel.setBackground(Color.cyan);

    JPanel cell = new JPanel();

    cell.setBackground(Color.gray);
    mazePanel.add(cell);

    cell.setBackground(Color.BLACK);
    mazePanel.add(cell);

    cell.setBackground(Color.red);
    mazePanel.add(cell);

    cell.setBackground(Color.GREEN);
    mazePanel.add(cell);

    frame.add(mazePanel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.pack();
    frame.setVisible(true);


}

Upvotes: 0

Views: 69

Answers (2)

ola
ola

Reputation: 912

        JFrame frame;
        JPanel mazePanel = new JPanel();
        frame = new JFrame("The Maze");
        frame.setSize(600, 600);
        mazePanel.setLayout(new GridLayout(2, 2));

        mazePanel.setBackground(Color.cyan);

        JPanel cell = new JPanel();
        JPanel cell2 = new JPanel();
        JPanel cell3 = new JPanel();
        JPanel cell4 = new JPanel();

        cell.setBackground(Color.gray);
        mazePanel.add(cell);

        cell2.setBackground(Color.BLACK);
        mazePanel.add(cell2);

        cell3.setBackground(Color.red);
        mazePanel.add(cell3);

        cell4.setBackground(Color.GREEN);
        mazePanel.add(cell4);

        frame.add(mazePanel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.pack();
        frame.setVisible(true);

You have to create separate cell objects like mentioned above. I believe this gives you what you are looking for.

Upvotes: 1

copeg
copeg

Reputation: 8348

A Component cannot be added to a Container more than once (eg cannot have multiple parents). In this case, what you see is the result of the last addition of the variable 'cell' to its parent mazePanel (green - together with the background color of mazePanel (cyan) due to the layout). If you wish to add multiple 'cells', then create new JPanel's with the appropriate background color and add them to the mazePanel

Upvotes: 3

Related Questions