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:
Joined: Jun 13, 2009
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.