GameOfLife()とPanelGridの2つのクラスがあります。 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コンポーネントを定義しません。私の[Java Swingの人生のジョン・コンウェイのゲーム](http://java-articles.info/articles/?p=504)の記事を見て、それがあなたにヒントを提供するかどうかを見てください。 –
'frame.setVisible(true);'をコンストラクタの最後の文として設定するのはどうですか? –
また、あなたの 'paintComponent'実装では' JPanel panel =新しいJPanel(); 'と' this.add(panel); 'それは大きなNO-NOです。ペイントコンポーネントは、ペイントのための* only *コンポーネントの構築/追加やレイアウトのためのものではありません。厳密にペインティングする。あなたはあなたの戦略を再考する必要があります。また、私たちの助けが必要な場合は、それが達成しようとしていることをより詳細に説明するのに役立つかもしれません。 –