在这个程序中,我们需要创建一个 8x8 网格的“LifeCell”小部件。讲师没有提到小部件必须是对象,Shape
所以我继续使用该GridLayout
课程。该类GridLayout
工作正常(据我所知,因为没有视觉辅助来确认。)该程序的目标是玩生命游戏,用户可以单击其中一个 LifeCell 小部件并在“状态”之间切换活着”或“死去”。
我的问题在很大程度上取决于让细胞被绘制。我的代码可能有问题,但我不能 100% 确定。
程序2.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
因为缺少更好的词是 type LifeCell
。我怎样才能画出每种LifeCell
不同的颜色?如果这对你们有任何意义,我可以尝试尽可能多地修改它。还有camickr,我会看看那个网站,谢谢。
可以在此处找到作业,以避免与我的问题和/或代码片段有关的任何和所有混淆。