Results 1 to 3 of 3
- 04-02-2009, 07:12 AM #1Member
- Join Date
- Apr 2009
- Rep Power
Best way to draw to screen & call game update method?
Hi, I'm currently porting a simple 2D game from C++ to Java, and for the most part I'm done.
Currently, for drawing the stuff to the JApplet, I'm drawing to an offscreen image, and then copying over the image by overriding the paint() method.
Also, to invoke the game update function (the game loop), I have a utility timer running every 10 msecs. This update function also calls the applets repaint() method when it's done.
The problems I'm having, is that the CPU usage of the applet is quite high - about 70%.
I used to be just drawing straight to the applet's Graphics from "getGraphics()", as hte nature of the game means not much changes each "update", so it's innefficient to keep drawing what doesn't change, however, whenever the window was minimized and then brought back up - what was drawn to the screen dissapeared. A solution to this would be ideal.
Also - one more problem. I'm handling the input of game through the applet by registering it as a mouselistener, however, sometimes clicks don't show up (i.e. the mouseClicked() method does not get invoked). Any insight to this problem would be helpful aswell.
1) Draw on a JPanel, not directly on the JApplet. Then add the JPanel to the JApplet, perhaps to the applet's contentPane
2) Override the JPanel's paintComponent method, and draw in this.
3) Don't get the Graphics object via getGraphics, it's better to passively paint in the JPanel's paintComponent method and use the Graphics object provided via the parameter.
4) Since you're coding in Swing, the timer should be a Swing Timer not a util Timer.
best of luck.
- 04-03-2009, 05:04 AM #3
You might miss mouse clicks if you're using the event dispatch thread for other stuff. Try not to have long-running code in event listeners and such, instead start long tasks on their own thread. See the guide to Threading in Swing.
As for high CPU usage - you might consider changing to an event-based model rather than a timer-based one if these changes don't sort it out. Of course that is likely to be rather difficult if you're porting and aren't intimately aware of the structural designs and functional specifications of the original code. Making sure you're not doing any busy waits - use synchronization; sleep() and notifyAll() - would be the first place to look though
Last edited by OrangeDog; 04-03-2009 at 05:08 AM.
- By Manfizy in forum New To JavaReplies: 3Last Post: 03-19-2009, 12:34 PM
- By frankjava1 in forum Java ServletReplies: 2Last Post: 10-24-2008, 04:20 AM
- By hussainzim in forum JavaServer Pages (JSP) and JSTLReplies: 1Last Post: 05-15-2008, 07:22 AM
- By jon80 in forum New To JavaReplies: 3Last Post: 05-07-2008, 08:37 AM
- By rhm54 in forum New To JavaReplies: 4Last Post: 02-07-2008, 08:51 AM