0

我有这个构造函数:

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) {       
        }
    });
}

ActionListeners 总是在“听” ;但是,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();
    }
}
4

1 回答 1

2

MouseListener只要您添加它的对象仍然存在并且假设您没有调用它, A就会继续工作removeMouseListener()。当您的程序运行并更改数据等时,您的侦听器内部代码的行为可能会发生变化(例如,设置了一个标志导致它忽略对另一个方法的调用),但侦听器将“始终运行”及其方法被调用。

(正如我在评论中提到的,您的问题可能与您在方法中所做的奇怪事情有关paintComponent()。)

于 2013-05-14T21:10:58.260 回答