Java SwingUtilities invoke later

Description

Java SwingUtilities invoke later

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.SwingUtilities;

public class Main extends JFrame {
   public static final int LENGTH = 100;
   public static final JList<String> COMPONENT = new JList<>();
   //  w  w w .  j  a  va2  s.  c  o  m
   public class CountingTask implements Runnable {
      public void run() {
         for (int i = 1; i <= LENGTH; i++) {
            // Add an item
            ((DefaultListModel<String>) COMPONENT.getModel()).clear();
            ((DefaultListModel<String>) COMPONENT.getModel()).addElement("At: "+i);
            // Force component repaint
            COMPONENT.repaint();
            COMPONENT.invalidate();
            COMPONENT.repaint();
            // Sleep for a little to give other threads a chance
            try {
               Thread.sleep(1);
            } catch (InterruptedException e) {
               e.printStackTrace();
            }
         }
      }
   }
   
   public Main() {
      DefaultListModel<String> listModel = new DefaultListModel<>();
      COMPONENT.setModel(listModel);
      getContentPane().add(COMPONENT);
      pack();
      setSize(300,500);
      setVisible(true);
      
      for (int t = 0; t < 16; t++) {
         SwingUtilities.invokeLater(new CountingTask());
      }
   }
   
   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() { new Main(); }
      });
   }
}



PreviousNext

Related