I\'m having an issue with Threads using netbeans Swing GUI. This is my first time really trying to develop a GUI for a backup program using Java\'s File System Notifier. I h
In support of davidbuzatto:
No, I think you miss under stood what InvokeLater
does. InvokeLater
ensures that the runnable is executed ON the ETD
. So basically, from what I can read, you've gone an put your long running, Event Blocking code right back in the ETD
. Only use InvokeLater
when you want to update the UI, use Threads or SwingWorker
when you want to actually do processing
void processEvents() throws IOException, InterruptedException
{
System.out.println("Entered processEvents");
// PLEASE ETD, PUT THIS AT THE END OF THE QUEUE AND EXECUTE
// SO I RUN WITHIN YOUR CONTEXT
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
// NOW RUNNING BACK ON THE ETD
System.out.println("Entered run");
list.add("test2");
list.repaint();
// NOW BLOCK THE ETD, SO NO MORE REPAINTS OR UPDATES WILL EVER
// OCCUR
while(true)
{
WatchKey key;
try
{
key = ws.take();
}
catch (InterruptedException x)
{
return;
}
Sorry for the caps, but I wanted the comments to standout.
1. Swing is Not Thread safe, but some methods like repaint(), setText()
are Tread Safe.
2. The main() method in Swing is Not Long Lived. It schedules the construction of GUI in the Event Dispactcher Thread and then quits. Now its the responsibility of the EDT to handle the GUI.
3. You must keep your Non-UI work on your Non-UI thread, out off the GUI thread, ie EDT.
4. Your main()
method should only do the work of making the JFrame visible, using EventQueue.invokeLater.
Eg:
public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
public void run(){
myFrame.setVisible(true);
}
}
}
5 SwingWorker is provided by Java to Synchronize the Work Output of the Non-UI thread on the GUI thread.
Swing is not thread safe, so, if you are tryng to update a UI in the same thread you will have the "application freeze" behavior. To solve this, you need to delegate the process of update the UI to another thread. This is made using SwingUtilities.invokeLater (Java 5 and prior) method and/or the SwingWorker class (since Java 6).
Some links:
Google search: https://www.google.com.br/search?q=swing+thread+safe