Results 1 to 2 of 2
Thread: Make a clickable moving image?
- 04-08-2011, 07:36 PM #1
Member
- Join Date
- Mar 2011
- Posts
- 13
- Rep Power
- 0
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?
Java 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(); } }
-
I would do things very differently. For one, I try to avoid painting directly in the JFrame but rather in the paintComponent method of a JPanel or JComponent. In your situation since you want a clickable graphic, I'd do it differently still by creating an ImageIcon from the Image, placing it in a JLabel, adding a MouseListener to the JLabel, adding the JLabel to a container (JPanel) that uses null layout, taking care to set its bounds, and then moving the JLabel in a Swing timer. I'd avoid using a Thread.sleep(...) in a Swing application, and I'd not use the update method for Swing graphics (that's for AWT programs). YMMV.
Similar Threads
-
Make shape rounding (moving in circle)
By mneskovic in forum New To JavaReplies: 8Last Post: 08-17-2010, 03:05 PM -
Problem in rotating and moving image at the same time
By Babar in forum Java 2DReplies: 3Last Post: 06-16-2010, 10:27 PM -
Moving an image on a JFrame
By jinkazama in forum AWT / SwingReplies: 3Last Post: 06-04-2010, 12:05 AM -
Putting clickable icons on an image
By szakee in forum AWT / SwingReplies: 3Last Post: 04-06-2009, 10:25 AM -
moving image - PROBLEM
By Triss in forum New To JavaReplies: 3Last Post: 01-17-2008, 06:52 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks