В рамках этой программы нам нужно создать сетку 8x8 виджетов «LifeCell». Инструктор не упомянул, что виджеты должны были быть объектами Shape
, поэтому я пошел дальше и использовал класс GridLayout
. Класс GridLayout
работает отлично (насколько мне известно, поскольку визуального содействия для подтверждения нет.) Цель программы - сыграть в игру «Жизнь», где пользователь может щелкнуть один из виджетов LifeCell и переключаться между состояния «живы» или «мертвы».
Мой вопрос в значительной степени зависит от того, как нарисовать клетки. Это может быть проблема с моим кодом, но я не уверен на 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);
}
Мне не нужно точное решение, чтобы исправить это, но я в конце концов пытаюсь заставить его работать.
Спасибо.
EDIT:
Я добавил больше сегмента класса Program2.java, завтра могу проверить, я иду спать, я ценю всю помощь, ребята.
РЕДАКТИРОВАТЬ # 2:
Моя настоящая путаница возникает, когда я заполняю свой кадр 8x8 GridLayout
каждой отдельной «ячейкой» из-за отсутствия лучших слов типа LifeCell
. Как я могу нарисовать каждый LifeCell
разных цветов? Если это вообще имеет какое-то значение для вас, ребята, я могу попытаться пересмотреть это столько, сколько смогу. И camickr, я посмотрю на этом сайте, спасибо.
Назначение можно найти здесь , чтобы избежать путаницы в отношении моего вопроса и / или фрагмента кода.