0
我有這樣的構造:保持一個MouseListener的始終運行
public Board(final boolean[][] board) {
this.board = board;
height = board.length;
width = board[0].length;
setBackground(Color.black);
button1 = new JButton("Run");
add(button1);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
isActive = !isActive;
button1.setText(isActive ? "Pause" : "Run");
}
});
button2 = new JButton("Random");
add(button2);
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setBoard(randomBoard());
}
});
button3 = new JButton("Clear");
add(button3);
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setBoard(clearBoard());
}
});
addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
board[e.getY()/multiplier][e.getX()/multiplier] = !board[e.getY()/multiplier][e.getX()/multiplier];
}
@Override
public void mouseReleased(MouseEvent e) {
}
});
}
的ActionListener
s的總是 '聽';但在點擊運行(button1
)後,MouseListener
停止「收聽」。爲什麼這個以及我如何讓MouseListener
保持收聽狀態?
如果它的任何使用,我也有這個paintComponent
類:
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
g.setColor(board[i][j] ? Color.green : Color.gray);
g.fillRect(j * multiplier, i * multiplier, multiplier - 1, multiplier - 1);
}
}
if (isActive) {
timer.start();
}
else {
timer.stop();
repaint();
}
}
考慮的變量名,比如'btnRun','btnClear'和'btnRandom'而不是'button1','button2'和'button3'。 – wchargin
什麼是'計時器'? – whiskeyspider
@whiskeyspider'定時器計時器=新計時器(500,this);' – LazySloth13