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 패널 = 새 JPanel();과'this.add (패널);'? 그것은 큰 NO-NO입니다. 페인트 구성 요소는 그림을 그리는 데만 사용되며 구성 요소를 작성/추가하거나 배치하지 않습니다. 엄격히 그림. 전략을 재고해야합니다. 또한, 우리에게 도움이 필요하다면, 당신이 달성하고자하는 것을 더 자세하게 설명하는 것이 도움이 될 수 있습니다. –