Reputation: 2487
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 ActionListener
s are always 'listening'; however the MouseListener
stops '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();
}
}
Upvotes: 0
Views: 262
Reputation: 12332
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.)
Upvotes: 2