简体   繁体   English

创建jpanels后更改其颜色

[英]Change color of jpanels after their creation

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. 我正在尝试制作一个GUI迷宫游戏,在计算机尝试解决迷宫的过程中,它会更改迷宫所在点的颜色。 The maze is made up of a JFrame with a JPanel (GridLayout). 迷宫由带有JPanel(网格布局)的JFrame组成。 In the grid is the JPanels that I need to change their colors. 在网格中是我需要更改其颜色的JPanels。 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? 有没有办法用其他方法改变p2的颜色? Or is there a better way to do it? 还是有更好的方法呢?

If your have the referee of JFrame then you can do it in this way. 如果您有JFrame的裁判,则可以通过这种方式进行。

    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 . 这里的6代表第二行和第三列,与JPanelJFrame中添加的顺序相同。

在此处输入图片说明


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() EventQueue.invokeLater()

    All GUI related things in java should always go through a single thread. Java中所有与GUI相关的事物都应始终通过单个线程。 The thread is our legendary AWT-EventQueue . 该线程是我们传奇的AWT-EventQueue Hence all GUI related actions should necessarily go through the AWT Event thread. 因此,所有与GUI相关的操作都必须经过AWT事件线程。 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? 阅读更多我们应该在Java桌面应用程序中使用EventQueue.invokeLater进行GUI更新吗?

  2. UIManager.setLookAndFeel() UIManager.setLookAndFeel()

    UIManager manages the current look and feel, the set of available look and feels. UIManager管理当前的外观和可用的外观集。

    Read more How to Set the Look and Feel 阅读更多内容如何设置外观

  3. JComponent#getPreferredSize() JComponent的#的getPreferredSize()

    Read more Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? 阅读更多我应该避免在Java Swing中使用set(Preferred | Maximum | Minimum)Size方法吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM