このプログラム内で、「LifeCell」ウィジェットの8x8グリッドを作成する必要があります。インストラクターはウィジェットが対象である必要があるとは言わなかったShape
ので、私は先に進んでGridLayout
クラスを使用しました。クラスはGridLayout
正常に機能します(確認する視覚的な補助がないため、私も知っています)。プログラムの目的は、ユーザーがLifeCellウィジェットの1つをクリックして、状態を切り替えることができる人生ゲームをプレイすることです。生きている」または「死んでいる」。
私の質問は、セルをペイントすることに大きく依存しています。コードに問題がある可能性がありますが、100%確信はありません。
Program2.java
public class Program2 extends JPanel implements ActionListener {
private LifeCell[][] board; // Board of life cells.
private JButton next; // Press for next generation.
private JFrame frame; // The program frame.
public Program2() {
// The usual boilerplate constructor that pastes the main
// panel into a frame and displays the frame. It should
// invoke the "init" method before packing the frame
frame = new JFrame("LIFECELL!");
frame.setContentPane(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.init();
frame.pack();
frame.setVisible(true);
}
public void init() {
// Create the user interface on the main panel. Construct
// the LifeCell widgets, add them to the panel, and store
// them in the two-dimensional array "board". Create the
// "next" button that will show the next generation.
LifeCell[][] board = new LifeCell[8][8];
this.setPreferredSize(new Dimension(600, 600));
this.setBackground(Color.white);
this.setLayout(new GridLayout(8, 8));
// here is where I initialize the LifeCell widgets
for (int u = 0; u < 8; u++) {
for (int r = 0; r < 8; r++) {
board[u][r] = new LifeCell(board, u, r);
this.add(board[u][r]);
this.setVisible(true);
}
}
LifeCell.java
public class LifeCell extends JPanel implements MouseListener {
private LifeCell[][] board; // A reference to the board array.
private boolean alive; // Stores the state of the cell.
private int row, col; // Position of the cell on the board.
private int count; // Stores number of living neighbors.
public LifeCell(LifeCell[][] b, int r, int c) {
// Initialize the life cell as dead. Store the reference
// to the board array and the board position passed as
// arguments. Initialize the neighbor count to zero.
// Register the cell as listener to its own mouse events.
this.board = b;
this.row = r;
this.col = c;
this.alive = false;
this.count = 0;
addMouseListener(this);
}
そしてここにpaintComponent
方法があります:
public void paintComponent(Graphics gr) {
// Paint the cell. The cell must be painted differently
// when alive than when dead, so the user can clearly see
// the state of the cell.
Graphics2D g = (Graphics2D) gr;
super.paintComponent(gr);
g.setPaint(Color.BLUE);
}
私はそれを修正するための正確な解決策を必要としませんが、私はそれを機能させることを試みています。
ありがとう。
編集:
Program2.javaクラスのセグメントをさらに追加しました。明日、ベッドに向かっていることを確認できます。すべてのヘルプ担当者に感謝します。
編集#2:
私の本当の混乱は、フレームに8x8のGridLayout
個々の「セル」を入力すると、より適切な単語がないためにタイプが発生しLifeCell
ます。どうすればそれぞれLifeCell
の異なる色を塗ることができますか?それが皆さんにとって意味があるのであれば、私はできる限りそれを修正しようと試みることができます。そしてcamickr、私はそのウェブサイトを見ていきます、ありがとう。
私の質問やコードスニペットに関する混乱を避けるために、ここで割り当てを見つけることができます。