如何在Java JFrame中制作一堆可点击的面板

时间:2019-04-25 14:23:35

标签: java jframe conways-game-of-life

我正在尝试使用JFrame重新创建Java中的生命游戏。我已经完成了大部分程序,但是这一件事困扰着我。如何制作一堆可单击的字段(面板),以便用户可以输入自己的图案,而不是由计算机每次随机生成图案?

1 个答案:

答案 0 :(得分:1)

您可以使用GridLayout布局管理器将所有JPanel放置在网格中,并为每个JPanel使用addMouseListener()添加MouseAdapter类的实例,以侦听鼠标单击以翻转其状态。 MouseAdapter的实例将覆盖mouseClicked(),并在该函数内翻转JPanel的状态。

这只是一个完整的示例,但这将是框架的创建并设置其布局管理器:

public static void main(String[] args) {
    JFrame frame = new JFrame();
    int width = 200, height = 200;
    frame.setSize(width, height);
    int rows = width/10, cols = height/10;
    frame.setLayout(new GridLayout(rows, cols));
    // add all the cells
    for(int j = 0; j < cols; j++) {
        for(int i = 0; i < rows; i++) {
            frame.add(new Cell(i, j));
        }
    }
    frame.setVisible(true);
}

然后对于每个单元格,我们都有此类的实例:

class Cell extends JPanel {
int row, col;
public static final int STATE_DEAD = 0;
public static final int STATE_ALIVE = 1;
int state = STATE_DEAD;

public Cell(int row, int col) {
    this.row = row;
    this.col = col;
    // MouseAdapter tells a component how it should react to mouse events
    MouseAdapter mouseAdapter = new MouseAdapter() {
        // using mouseReleased because moving the mouse slightly
        // while clicking will register as a drag instead of a click
        @Override
        public void mouseReleased(MouseEvent e) {
            flip();
            repaint(); // redraw the JPanel to reflect new state
        }
    };
    // assign that behavior to this JPanel for mouse button events
    addMouseListener(mouseAdapter);
}

// Override this method to change drawing behavior to reflect state
@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    // fill the cell with black if it is dead
    if(state == STATE_DEAD) {
        g.setColor(Color.black);
        g.fillRect(0, 0, getWidth(), getHeight());
    }
}

public void flip() {
    if(state == STATE_DEAD) {
        state = STATE_ALIVE;
    } else {
        state = STATE_DEAD;
    }
}

}

或者,您可以覆盖一个JPanel的paintComponent()方法,并执行上述操作,但也要使用addMouseMotionListener(),这样一来,您的面板就可以跟踪鼠标所在的绘制网格单元,并且可以控制方式他们被绘制。