2010-01-13 48 views

回答

1

嘗試使用SwingUtilities.invokeLater或invokeAndWait。

像下面的代碼。

希望它有幫助。

import java.awt.BorderLayout; 

import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.SwingUtilities; 

public class LabelUpdater { 
    public static void main(String[] args) { 
     LabelUpdater me = new LabelUpdater(); 
     me.process(); 
    } 

    private JLabel label; 

    private void process() { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       JFrame frame = new JFrame(); 
       frame.setContentPane(new JPanel(new BorderLayout())); 
       label = new JLabel(createLabelString(5)); 
       frame.getContentPane().add(label); 
       frame.setSize(300, 200); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 

     snooze(); 
     for (int i = 5; i >= 1; i--) { 
      final int time = i - 1; 
      snooze(); 
      SwingUtilities.invokeLater(new Runnable() { 

       public void run() { 
        label.setText(createLabelString(time)); 

       } 

      }); 

     } 

    } 

    private void snooze() { 
     try { 
      Thread.sleep(1000); 
     } catch (InterruptedException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 
    } 

    private String createLabelString(int nbSeconds) { 
     return "Still " + nbSeconds + " seconds to wait"; 
    } 
} 
+0

謝謝它的工作.. :) – nicky 2010-01-13 11:32:53

1

使用javax.swing.Timertutorial)。這將通過在事件派發線程上執行來確保線程安全。

public class TimerDemo { 
    public static void main(String[] args) { 
    final int oneSecondDelay = 1000; 
    final JLabel label = new JLabel(Long.toString(System.currentTimeMillis())); 
    ActionListener task = new ActionListener() { 
     @Override public void actionPerformed(ActionEvent e) { 
     label.setText(Long.toString(System.currentTimeMillis())); 
     } 
    }; 
    new javax.swing.Timer(oneSecondDelay, task).start(); 
    JFrame frame = new JFrame(); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setLayout(new FlowLayout()); 
    frame.add(label); 
    frame.pack(); 
    frame.setVisible(true); 
    } 
} 
相關問題