Re: How to change JPanels?
Eric <e.d.programmer@gmail.com> wrote in news:f6c341f1-f28d-4be5-b3cf-
b820eb68a9c8@o39g2000prb.googlegroups.com:
<snip>
Eric <e.d.program...@gmail.com> wrote in news:3ace5bbb-ab88-4d11-af96-
Ok, it seems the actual problem is that gui commands will not redraw a
gui screen while the program is running a listener action event.
I wrote the class as SSCCE.
<snip>
As you said, "gui commands will not redraw a gui screen while the program
is running a listener action event".
The SSCCE was very helpful. If you replace the class
with the following, you will see that things are actually working well:
private class FirstItemListener implements ActionListener {
int flip = 0 ;
public void actionPerformed( ActionEvent ev) {
if ((flip%2)==0) {
loadTwo() ;
} else {
loadOne() ;
}
flip++ ;
}
}
(You must also insert the final '}' that was missing from the posting.)
You have broken two important rules regarding Swing programming:
1) Time-consuming tasks should not be run on the Event Dispatch Thread.
Otherwise the application becomes unresponsive.
2) Swing components should be accessed on the Event Dispatch Thread only.
[Copied from the Javadoc for javax.swing.SwingWorker]
Do NOT perform long-running tasks within an ActionListener. The
ActionListener is executed on the EDT (Event Dispatch Thread), the same
Thread that is used for repainting the GUI. Learn to use
javax.swing.SwingWorker or soemthing similar to get your long-running
actions executed on a Thread other than the EDT.
The code:
loadTwo();
long t0, t1;
t0 = System.currentTimeMillis();
do {
t1 = System.currentTimeMillis();
} while ((t1 - t0) < (3000));
loadOne();
}
constitutes a long-running task that will prevent GUI updates.
The method createWindow() should be executed on the EDT to avoid breaking
rule #2. Use javax.swing.SwingUtilities.invokeAndWait or
javax.swing.SwingUtilities.invokeLater() to get code executed on the EDT.
Yes, your SSCCE seems to be working despite breaking rule #2, but a more
complex prpogram is likely to break in interesting ways that are extremely
difficult to diagnose.
See
http://download.oracle.com/javase/tutorial/uiswing/concurrency/index.html
for more information.
Good luck!