This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
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.
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” (Mosher's Law of Software Engineering)
“If debugging is the process of removing bugs, then programming must be the process of putting them in.” (Edsger Dijkstra)
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.
- 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?