[英]How to make a bunch of clickable panels in Java JFrame
我正在尝试使用JFrame在Java中重新创建生命游戏。 我已经完成了大部分程序,但是这一件事困扰着我。 如何制作一堆可单击的字段(面板),以便用户可以输入自己的图案,而不是每次计算机随机生成图案?
您可以使用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(),这样一来,您的面板就可以跟踪鼠标所在的绘制的网格单元,并且可以控制它们的绘制方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.