This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js and have Paul Jensen on-line!
See this thread for details.
Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Simple Animation.  RSS feed

 
jin kazama
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2787
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!