1
我有2个类:GameOfLife()和PanelGrid。在创建panelgrid的新对象时,不会调用(覆盖的)方法paintComponent。将“repaint()”放在构造函数中也不起作用。未由构造函数调用paintcomponent或创建对象时
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class GameOfLife {
JFrame frame = new JFrame("Game of life");
PanelGrid panelGrid;
void buildIt() {
frame.setSize(600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(buttonStart, BorderLayout.SOUTH);
frame.add(buttonStop, BorderLayout.NORTH);
panelGrid = new PanelGrid();
panelGrid.setOpaque(true);
frame.add(panelGrid);
}
public static void main(String[] args) {
new GameOfLife().buildIt();
}
}
class PanelGrid extends JPanel implements ActionListener {
Timer timer;
int delay;
JLabel label;
int height; // get length from the file
int width; //get width of array from the file
//constructor
public PanelGrid() {
delay = 1000;
timer = new Timer(delay, this);
width = 4;
height = 5;
//if there exists a file with an initial configuration, initial[][], width and height are updated.
//if not, the default array is used
readInitial();
//repaint(); putting repaint() here din't make a difference.
}
@Override
public void paintComponent(Graphics g) {
System.out.println("if you read this, the method is called");
super.paintComponent(g); //erases panel content
this.setLayout(new GridLayout(width, height));
for (int r = 0; r < height; r++) {
for (int c = 0; c < width; c++) {
JPanel panel = new JPanel();
if (grid[r][c].isAlive() == true) {
panel.setBackground(Color.BLACK);
} else {
panel.setBackground(Color.WHITE);
}
this.add(panel);
}
}
//the rest of this class I have left out for clarity
}
}
你的代码甚至没有编译。 PanelGrid类中的动作侦听器缺失。网格未定义。您不要在paintComponent方法中定义Swing组件。看看我的[John Conway的Java Swing中的生活游戏](http://java-articles.info/articles/?p=504)文章,看看它是否提供了任何提示。 –
如何设置'frame.setVisible(true);'作为构造函数中的最后一个语句? –
也......在你的'paintComponent'实现中''JPanel panel = new JPanel();''和'this.add(panel);'这是一个很大的NO-NO。绘画组件仅*用于绘画,而不用于构建/添加组件或将其展开。严格的绘画。你必须重新考虑你的策略。此外,如果您需要我们的帮助,这可能有助于更详细地解释您尝试实现的目标。 –