I\'m trying to code a simple game in Java. The basic structure is a single JFrame
with different JPanels
that I add/remove at different times. At s
never really never use Thread.sleep(1000);
during EDT, this code caused freeze on GUI is un_resposible, untill a new event invoke EDT or mouse hover over can alive this container too
1) there are two ways how to dealy any event(s) in the Swing GUI, by implements
Swing Timer
delaying by using Thread.sleep(1000);
in the SwingWorker
You can start some code with a time delay using TimerTask:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
invokeLater(); // This starts after [delay] ms
// and - if given - will run every [period] ms.
}
}, delay, period);
You could solve your problem with this, though it won't be a pretty solution.
// edit: (see comments) you should synchronize accesses to the gui properly, else it will give you errors.
The layout and painting must be done in EDT. Use SwingUtilities.invokeAndWait
to call the validate()
and repaint()