保持MouseListener始终运行

时间:2013-05-14 20:35:46

标签: java swing awt 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总是'倾听';但是,点击“运行”(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();
    }
}

1 个答案:

答案 0 :(得分:2)

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

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