This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Nothing seems to be moving?

 
john price
Ranch Hand
Posts: 495
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am just starting out with Java 2D. I created 3 sample 2D objects, a line, rectangle, and ellipse. They show up immediately when it launches. Then, nothing happens. What I wanted to happen is to have the objects appear to be moving. This is done through a timer.

Thanks,
cc11rocks
 
Rob Spoor
Sheriff
Pie
Posts: 20550
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) Why stop and restart the timer? Just let it run.
2) Don't override paint; override paintComponent instead (and keep it protected).
3) If you do override paint, call super.paint(g) as the first line. Likewise for paintComponent; the first line should be super.paintComponent(g).
4) In your paint method you reset "q", "w", "e" and "r" to their default values. You probably want to move these 4 lines to the constructor. Likewise for the timer initialization and starting. paint / paintComponent should only perform drawing, not contain business logic.
5) You can replace the entire WindowAdapter code with one line:
6) What's the user for variable "retard"? Are you trying to insult someone here? BeNice.

If you've fixed these issues your code will appear to draw nothing. That's because your interval is so short that the drawing will be outside the visible part of your frame within a few dozen milliseconds.
 
Stephan van Hulst
Bartender
Pie
Posts: 5898
63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
- Why do you import Timer when you import all of javax.swing?
- Why does your class name start with lower case?
- Why does your class implement ActionListener? You should make a separate listener inside your class.
- Why are your fields not private?
- Why are you using paint() instead of paintComponent()?
- Why are you using the paint() method to initialize your values? Why are you not using a constructor?
- Why do you create a new timer each time paint() is invoked?
- Why do you stop and start your timer instead of just letting it run?

[edit]

Slower than Rob
 
john price
Ranch Hand
Posts: 495
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you guys!
cc11rocks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic