Make a clickable moving image?
I have an image moving across the screen and I would like to make it clickable. Everything I have tried does not work.
I have tried adding an ActionListener, MouseListener, using an ImageIcon and JButton instead of Image.
How can I make the moving image clickable?
Code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Main extends JFrame implements ActionListener{
int xPos = -50;
int yPos = 300;
Image bob;
Image bobImage;
Graphics bobGraphics;
public Main() {
try {
bob = Toolkit.getDefaultToolkit().getImage("spongeRun.png");
}
catch(Exception e) {}
setSize(800,600);
setVisible(true);
moveImage();
}
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g) {
int width = getWidth();
int height = getHeight();
if (bobImage == null) {
bobImage = createImage(width, height);
bobGraphics = bobImage.getGraphics();
}
bobGraphics.clearRect(0, 0, width + 1, height + 1);
bobGraphics.drawImage(bob, xPos, yPos, this);
g.drawImage(bobImage, 0, 0, this);
}
void moveImage() {
for ( int i = 0 ; i < 500 ; i++ ){
xPos +=2;
repaint();
try { Thread.sleep(5); }
catch (InterruptedException e) { System.err.println("poop!"); }
}
}
public void actionPerformed(ActionEvent e){
}
public static void main(String[] args) {
Main me = new Main();
}
}