【发布时间】:2015-03-25 04:10:24
【问题描述】:
您好,我试图在 Java 中创建一个网格并绘制每个单元格,但我不知道我做错了什么。每个单元格都是一个 JPanel,我将每个单元格添加到 mazePanel。之后,将 mazePanel 添加到框架中。但只能得到下图所示的结果:
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);
}
【问题讨论】:
-
您只是一遍又一遍地更改同一个 JPanel 对象。您必须创建新对象,而不是在同一个对象上调用 setBackground。