我有这个构造函数:
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
总是'倾听';但是,点击“运行”(MouseListener
)后,button1
会停止“收听”。为什么这样,我如何让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();
}
}
答案 0 :(得分:2)
只要您添加的对象仍然存在并且假设您没有在其上调用MouseListener
,removeMouseListener()
将继续有效。当您的程序运行并更改数据等时,侦听器内部代码的行为可能会发生变化(例如,设置了一个标志,导致它忽略对另一个方法的调用),但是侦听器将“始终运行”及其方法将被召唤。
(正如我在评论中提到的,您的问题可能与您在paintComponent()
方法中所做的奇怪事情有关。)