Keeping a MouseListener always running

感情迁移 提交于 2019-12-11 19:17:44

问题


I have this constructor:

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

The ActionListeners are always 'listening'; however the MouseListenerstops 'listening' after I click Run (button1). Why is this and how do I make MouseListener remain listening?

If it's any use, I also have this paintComponent class:

@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:


A MouseListener will continue to work as long as the object you added it to is still alive and assuming you haven't called removeMouseListener() on it. As your program runs and changes data and such, the behavior of the code inside your listener may change (e.g., a flag is set causing it to ignore a call to another method), but the listener will be "always running" and its methods will be called.

(As I mentioned in my comment, your problem likely has to do with the strange things you are doing in your paintComponent() method.)



来源:https://stackoverflow.com/questions/16552392/keeping-a-mouselistener-always-running

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!