Ok so I have a problem with the code below, mostly everything works as I would expect but the stoplight picture doesn't show up until I click one of the buttons (red, yellow, or green) twice. The really odd part is the step variable gets updated which is in the same code block that initiates the drawing of the light. Once any button has been pressed twice that image shows properly and promptly after any other button presses. Anotherwards the app works exactly as it should once I press each of the buttons twice. It's my first posting here so I apologize if this is the wrong forum or improperly formatted.
That whole thing you're doing, where you call getGraphics() in an event handler and do your painting there -- that just isn't how it's done. Not only will strange things happen (as you've observed) the application won't update properly when you resize, cover, minimize or move the window.
The proper thing to do is to set flags and other state variables in your event handlers, override the paintComponent() method of a Swing component, and use the Graphics passed as an argument to that mehtod to do all your painting.
Ok, I think I understand. You're saying I should not call getGraphics() in the event but just setup my variables there and then pass them to methods to perform the draw. I agree with this and understand it's a better approach. I've altered my code to the following but I'm still getting the lag where I have to click the button twice to get the graphic to show up so it may be unrelated.
Here's the new code:
I've removed the timer that facilitates the animation of the car while the light is yellow/green out to simplify/troubleshoot but still no luck. If anyone sees any problems here please let me know, I really want to learn how to do this the right way.
author and iconoclast
Naw, you're still doing the same thing. Check out this tutorial. By the time they get to the program named SwingPaintDemo3, they're doing exactly what I'm recommending: set variables in your event handlers and call repaint(); then override paintComponent(), and use the variables to do the painting in there.
Joined: Jun 14, 2008
Thanks again Ernest, I'm currently working through the tutorial you provided but I just wanted to let you know I appreciate your help