HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

"Thread-Safe GUIs With Swing, by Neal Ford"
Vol. 6, Issue 5, p. 64

	


Listing 1
 
import java.awt.*; 
import java.awt.event.*; 
import java.util.*; 
import javax.swing.*; 

public class BadThread { 
    public static void main(String[] args) { 
        JFrame frame = new TestFrame(); 
        frame.show(); 
    } 
} 

class TestFrame extends JFrame { 
    public TestFrame() { 
        setTitle("Bad Thread Example"); 
        setSize(400,300); 
        setDefaultCloseOperation( 
                JFrame.EXIT_ON_CLOSE); 
        model = new DefaultListModel(); 

        JList list = new JList(model); 
        JScrollPane scrollPane = 
                new JScrollPane(list); 

        JPanel p = new JPanel(); 
        p.add(scrollPane); 
        getContentPane().add(p, "Center"); 

        JButton b = new JButton("Fill List"); 
        b.addActionListener(new ActionListener() { 
            public void actionPerformed( 
                    ActionEvent event) { 
                new WorkerThread(model).start(); 
            } 
        }); 
        p = new JPanel(); 
        p.add(b); 
        getContentPane().add(p, "North"); 
    } 

    private DefaultListModel model; 
} 

class WorkerThread extends Thread { 
    public WorkerThread(DefaultListModel aModel) { 
        model = aModel; 
        generator = new Random(); 
    } 

    public void run() { 
        while (true) { 
            Integer i = 
                new Integer(generator.nextInt(10)); 

            if (model.contains(i)) 
                model.removeElement(i); 
            else 
                model.addElement(i); 

            yield(); 
        } 
    } 

    private DefaultListModel model; 
    private Random generator; 
} 

Listing 2
 
import java.awt.*; 
import java.awt.event.*; 
import java.util.*; 
import javax.swing.*; 

public class GoodThread { 
    public static void main(String[] args) { 
        JFrame frame = new TestFrame(); 
        frame.show(); 
    } 
} 

class TestFrame extends JFrame { 
    public TestFrame() { 
        setTitle("Good Thread Example"); 
        setSize(400,300); 
        setDefaultCloseOperation( 
                JFrame.EXIT_ON_CLOSE); 
        model = new DefaultListModel(); 

        JList list = new JList(model); 
        JScrollPane scrollPane = 
                new JScrollPane(list); 

        JPanel p = new JPanel(); 
        p.add(scrollPane); 
        getContentPane().add(p, "Center"); 

        JButton b = new JButton("Fill List"); 
        b.addActionListener(new ActionListener() { 
            public void actionPerformed( 
                    ActionEvent event) { 
                new WorkerThread(model).start(); 
            } 
        }); 
        p = new JPanel(); 
        p.add(b); 
        getContentPane().add(p, "North"); 
    } 

    private DefaultListModel model; 
} 

class WorkerThread extends Thread { 
    public WorkerThread(DefaultListModel aModel) { 
        model = aModel; 
        generator = new Random(); 
    } 

    public void run() { 
        while (true) { 
            final Integer i = 
                new Integer(generator.nextInt(10)); 
            EventQueue.invokeLater(new Runnable() { 
                public void run() { 
                    if (model.contains(i)) 
                        model.removeElement(i); 
                    else 
                        model.addElement(i); 
                } 
            }); 
            yield(); 
        } 
    } 

    private DefaultListModel model; 
    private Random generator; 
} 
  
  
  
  
  
  

Listing 3
 
abstract class WorkerThread extends Thread { 
  protected SwingGuiFrame ui; 
  private boolean terminateRequested = false; 

  public WorkerThread(SwingGuiFrame ui) { 
    this.ui = ui; 
  } 

  public void terminate() { 
    terminateRequested = true; 
  } 

  public boolean isTerminateRequestd() { 
    return terminateRequested; 
  } 
  

Listing 4
 
class DeleteThread extends WorkerThread { 
  private static final String PREFIX = 
      "e:/temp/test"; 

  DeleteThread(SwingGuiFrame ui) { 
    super(ui); 
  } 

  public void run() { 
    File a = new File(PREFIX); 
    String fileList[] = a.list(); 
    ui.initDeleteProgress(fileList.length); 
    int numFiles = fileList.length; 
    for (int i = 0; i < fileList.length; i++) { 
      File f = new File(PREFIX + '/' + 
          fileList[i]); 
      if (f.delete()) { 
        System.out.println("Deleted file" + 
            fileList[i]); 
      } 
      EventQueue.invokeLater(new Runnable() { 
        public void run() { 
          ui.updateDeleteProgress(); 
        } 
      }); 
      if (isTerminateRequestd()) { 
        return; 
      } 
      yield(); 
    } //for 
    ui.copyThread = new CopyThread(ui); 
    ui.copyThread.start(); 
  } 
} 
  

Listing 5
 
class CopyThread extends WorkerThread { 
  String filesToCopy[]; 
  private static final String PATH = 
      "d:/jdk1.3/demo/jfc/SwingSet2/src/"; 
  private static final String OUTPUT_PATH = 
      "e:/temp/test/"; 

  CopyThread(SwingGuiFrame ui) { 
    super(ui); 
    File srcDir = new File(PATH); 
    filesToCopy = 
        new String[srcDir.list().length]; 
    filesToCopy = srcDir.list(); 
    ui.initCopyProgress(filesToCopy.length); 
  } 

  public void run() { 
    int numFiles = filesToCopy.length; 
    for (int i = 0; i < numFiles; i++) { 
      System.out.println("Copying file:" + 
          filesToCopy[i]); 
      copyFile(filesToCopy[i]); 
      EventQueue.invokeLater(new Runnable() { 
        public void run() { 
          ui.updateCopyProgress(); 
        } 
      }); 
      if (isTerminateRequestd()) { 
        return; 
      } 
      yield(); 
    } 
  } 

  private void copyFile(String fileToCopy) { 
    BufferedInputStream bis = null; 
    BufferedOutputStream bos = null; 
    try { 
      File in = new File(PATH + fileToCopy); 
      File out = new File( 
          OUTPUT_PATH + fileToCopy); 
      FileInputStream fis = 
          new FileInputStream(in); 
      bis = new BufferedInputStream(fis, 256); 
      FileOutputStream fos = 
          new FileOutputStream(out); 
      bos = new BufferedOutputStream(fos); 
      while (bis.available() > 0) { 
        bos.write(bis.read()); 
      } 
      bos.flush(); 
    } catch (IOException ioe) { 
      System.out.println(ioe.getMessage()); 
      JOptionPane.showMessageDialog( 
          new Frame(), ioe.getMessage(), 
          "File Error", 
          JOptionPane.ERROR_MESSAGE); 
    } finally { 
      try { 
        bis.close(); 
        bos.close(); 
      } catch (IOException ignored) { 
      } //catch 
    } //finally 
  } 
} 


  
 
 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.