2016-11-07 44 views
0

我想用線程創建一個倒數計時器(這是我被告知要嘗試的)。我確實製作了UI和所有,但是一旦我添加了線程就凍結了。我試過使用Thread.yield(),但它沒有奏效。我試圖做的invokeLater()把戲,我看到了一個不同的問題,但它不斷給我不能convert void to Thread線程在做倒計時時凍結UI

每次經過UI後應該更新JTextField。

field = new JTextArea();  
Button = new JButton(); 
Button.addActionListener 
(
    new ActionListener() 
    { 
     public void actionPerformed(ActionEvent ae) 
     { 
      for (int i = Integer.parseInt(field.getText()); i >= 0; i--) 
      { 
       try 
       { 
        Thread.sleep(1000); 
       } 
       field.setText(Integer.toString(i)); 
      } 
     } 
    } 
); 
+3

你不能睡在UI線程上。 – SLaks

+0

你可能想看看這一個http://stackoverflow.com/questions/40265427/updating-swt-periodically-causes-gui-to-freeze –

+0

請詳細說明我還挺新鮮的使用線程D: – Bruce

回答

1

你根本沒有使用線程。試試這個:

field = new JTextArea();  
    Button = new JButton(); 
     Button.addActionListener 
     (
      new ActionListener() 
      { 
       public void actionPerformed(ActionEvent ae) 
       { 
        new Thread() {public void run() { 
         for (int i = Integer.parseInt(field.getText()); i >= 0; i--) 
         { 
          try 
          { 
           Thread.sleep(1000); 
          } 
          field.setText(Integer.toString(i)); 
         } 
        }}.start(); 
       } 
      } 
     ); 
+0

哦,我的天啊,你是一個生活者!非常感謝!!我已經在這個幾個小時了,我不能讓這一個去。我很抱歉啞巴錯誤D: – Bruce

0

「Swing事件處理代碼運行在被稱爲事件調度線程一個特殊的線程。調用Swing方法也運行在這個線程大多數代碼,這是必要的,因爲大多數Swing對象的方法是不是」線程安全「:從多個線程中調用它們會有線程干擾或內存一致性錯誤的風險,某些Swing組件方法在API規範中標記爲」線程安全「;可以從任何線程安全地調用這些方法,所有其他Swing組件方法必須從事件中調用調度線程忽略此規則的程序可能在大多數情況下都能正常運行,但會遇到難以重現的難以預料的錯誤。「 - 來自https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html

事件調度程序線程是swing的基礎知識。使用工作線程。