2012-09-07 42 views
0

有誰知道如何每5次更新一次jTextfield?自動。所以不需要用戶輸入。它用於更新文本字段中的時間。這是我嘗試過的,但後來我的程序凍結了。自動更新jtextfield

while(true){ 
         Thread.sleep(1000); 
         txtCheck.setText(convert.getCheck()); 
         System.out.println("Ja"); 
         } 

轉換是一個線程,我試圖拋出一個異常但失敗,導致Eclise說線程不能拋出異常。

Convert.getCheck:

public String getCheck() { 
     return check; 
    } 
+0

什麼在convert.getCheck() – CloudyMarble

+1

這哪裏是while循環您正在顯示?在main()中,在JFrame中,在JPanel中? – jeff

回答

3

你想用一個Swing Timer對象。這裏是一個Oracle tutorial

首先,你需要讓你的類實現ActionListener接口。在你的類的內部,你還需要實現一個actionPerformed()方法。最後,你應該啓動計時器在main()函數或某處

timer = new Timer(5000, MyClass); 
timer.setInitialDelay(pause); 
timer.start(); 

你會再實現你的類,如:

public class MyClass implements ActionListener 
{ 
    ... 

    void actionPerformed(ActionEvent e) { 
     /* 
     This is called every time the timer fires, put your code here 
     */ 
    } 
} 
+1

非常感謝你!完美的作品! –