开发者

Display objects in JFrame one at a time, or frame by frame

I've made a program in Java (eclipse) that displays squares and triangles on a grid using JFrame. The program determines where the objects go in a "for loop". I would like to have the objects appear one at a time (in a frame by frame type of approach). It seems like a "sleep loop" should be used to solve this problem. However I feel that a lack of understanding of java.awt*; is causing me problems. I adding the following to my "for loop"

try

{

Thread.sleep(1000); // do nothing for 1000 miliseconds (1 second)

}

catch(InterruptedException e)

{

e.printStackTrace();

}

The program waits, but draws the objects all at once after it is done sleeping. I have gone through my program and found that this "sleep" command is working to some extent (waiting before processing the next command) I pu开发者_开发问答t a println statement within said "for loop" to test it and the program waits one second before printing each println. But I don't know why JFrame draws everything only once at the end. Should I be using something like repaint() every time I want to display a new frame?

MY project structure is 3 classes. Main which simply calls DisplayFrame. DisplayFrame which sets up the Frame. And MyComponent which contains my "for loop" and the "sleep command".

Any help would be appreciated.


There is a tutorial here that uses a Timer to update an image at regular intervals. The example program is an applet, but the principle is the same.


sleep is probably a bad idea. Use a Timer instead:

http://download.oracle.com/javase/6/docs/api/javax/swing/Timer.html

From your description it is a little hard to guess what is going on, but I'm almost sure at least one of two bad things is happening:

  • you are sleeping in the EDT (Event Dispatch Thread) this locks the complete GUI and might be the reason for you not seeing any updates during sleep.

  • you are changing swing components from outside the EDT which is a sure way into concurrency hell.

Make sure you follow this approach:

Setup a Time to call you in the desired time intervall ( lets say every 0.1 seconds). In the method that is called manipulate you component/object to reflect the new state and call repaint.

let us know if it works. I'm not exactly sure about the repaint call ... might be wrong ..


Interestingly enough, the Applet Tutorial at the Oracle site has an example of an applet that performs an animation using SwingWorkers and Timers. Perhaps it can be useful to you.

Or you can take control of the rendering of the JFrame using concepts from the gaming world, as explained here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜