I have a circle being repainted continually to show animation. I would like to have the circle flash different colors if clicked. When I tried implementing MouseListener to get a mouseClicked event, it did not work. I believe that is due to the constant repainting. Is there another way to have this circle bounce around and still catch a mouse click? I added a KeyEvent to test, and it worked fine. There is no "main" as this was called from another program.
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.Random;
import java.util.Timer;
public class Catch extends Canvas {
int xCor, yCor, xMove, yMove;
Color currentColor;
Random ranNumber;
boolean flashing = false;
public Catch() {
enableEvents(java.awt.AWTEvent.KEY_EVENT_MASK);
requestFocus();
xCor = 500;
yCor = 350;
xMove = 5;
yMove = 5;
currentColor = Color.black;
ranNumber = new Random();
Timer t = new Timer(true);
t.schedule(new java.util.TimerTask() {
public void run() {
animate();
repaint();
}
}, 10, 10);
}
public void paint(Graphics g) {
g.setColor(currentColor);
g.fillOval(xCor, yCor, 20, 20);
}
public void processKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
flashing = !flashing;
}
}
}
public void animate() {
xCor += xMove;
yCor += yMove;
// and bounce if we hit a wall
if (xCor < 0 || xCor + 20 > 1000) {
xMove = -xMove;
}
if (yCor < 0 || yCor + 20 > 700) {
yMove = -yMove;
}
if (flashing) {
int r = ranNumber.nextInt(256);
int g = ranNumber.nextInt(256);
int b = ranNumber.nextInt(256);
currentColor = new Color(r, g, b);
}
}
public boolean isFocusable() {
return true;
}
}