MouseClicked Stop Animation
I'm trying to have the animation stop when the mouse button is clicked and start again once the mouse button is clicked again. But when I run it it stops with the first click and then will only start again if the mouse button is held down or it will start then immediately stop. Any help would be appreciated.
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ReboundPanelMouse extends JPanel
{
private final int WIDTH = 300, HEIGHT = 100;
private final int DELAY = 20, IMAGE_SIZE = 35;
private ImageIcon image;
private Timer timer;
private int x, y, moveX, moveY;
public ReboundPanelMouse()
{
timer = new Timer(DELAY, new ReboundListener());
addMouseListener (new StopListener());
image = new ImageIcon ("happyFace.gif");
x = 0;
y = 40;
moveX = moveY = 3;
setPreferredSize (new Dimension(WIDTH, HEIGHT));
setBackground (Color.black);
timer.start();
}
public void paintComponent (Graphics page)
{
super.paintComponent (page);
image.paintIcon (this, page, x, y);
}
private class ReboundListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
x += moveX;
y += moveY;
if (x <= 0 || x >= WIDTH-IMAGE_SIZE)
moveX = moveX * -1;
if (y <= 0 || y >= HEIGHT-IMAGE_SIZE)
moveY = moveY * -1;
repaint();
}
}
/
public class StopListener extends MouseAdapter
{
// Represents the action listener for the timer.
public void mouseClicked (MouseEvent event)
{
if (event.getButton() == MouseEvent.BUTTON1)
{
timer.stop();
}
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
if (evt.getButton() == MouseEvent.BUTTON1)
{
timer.start();
removeMouseListener(this);
}
}
});
}
}
}