permaculture playing cards
The moose likes Swing / AWT / SWT and the fly likes Simple Animation. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Simple Animation." Watch "Simple Animation." New topic

Simple Animation.

jin kazama

Joined: Mar 09, 2010
Posts: 7
Hi There

I am trying to learn some simple animation with Java and swing. The code below should create a frame and add a simple graphic to the screen. I have then added a Key Listener to capture the left and right cursor keys.

When the left or right key is pressed the image should move left or right. Currently it draws the image onto the frame and that is all I get, your advise is appreciated:

Rob Camick
Ranch Hand

Joined: Jun 13, 2009
Posts: 2452
1) First you need to learn the basics of doing custom painting. Read the section from the Swing tutorial on Custom Painting.

2) There is no need to create an infinite loop. The GUI will repaint itself when you repaint the image.

3) Also, KeyEvents are only received by components that have focus. By default a panel does not get focus, so you need to make the panel focusable. However, you should NOT be using KeyEvent to handle the left/right KeyStrokes. You SHOULD be using Key Bindings. Again the Swing tutorial has a section that explains what Key Bindings are.

Happy reading.
I agree. Here's the link:
subject: Simple Animation.
jQuery in Action, 3rd edition