該程序寫入從0到1000的計數,但它只是直接到1000而不顯示計數過程。我使用進度條和Thread.sleep()
方法編寫了類似的代碼,並且它完美地工作。在Swing中遇到Thread.sleep的問題
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JPanel;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class project extends JFrame implements ActionListener {
JButton CountUpButton = new JButton("Count up");
JButton CountDownButton = new JButton("Count Down");
JButton ResetButton = new JButton("Reset");
JTextField NumberField = new JTextField();
int count = 0;
public project(){
setLayout(new GridLayout(1, 4));
setSize(500, 300);
add(NumberField);
add(CountUpButton);
add(CountDownButton);
add(ResetButton);
CountUpButton.addActionListener(this);
CountDownButton.addActionListener(this);
ResetButton.addActionListener(this);
NumberField.setText("0");
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent a){
if(CountUpButton.hasFocus()){
count = Integer.parseInt(NumberField.getText());
try{
while(count < 1000){
count = count + 1;
NumberField.setText(Integer.toString(count));
Thread.sleep(100);
}
}catch(InterruptedException r){
r.printStackTrace();
}
}
if(CountDownButton.hasFocus()){
count = Integer.parseInt(NumberField.getText());
try{
while(count > 0){
count -= 1;
NumberField.setText(Integer.toBinaryString(count));
Thread.sleep(100);
}
}catch(InterruptedException r){
r.printStackTrace();
}
}
if(ResetButton.hasFocus()){
NumberField.setText("0");
}
}
public static void main(String args[]){
new project();
}
}
這是一個瘋狂的猜測,但由於JTextFields通常有一些初始值,然後由用戶修改,並且不希望像這樣以編程方式進行修改,也許您必須明確重新繪製它?只是一個猜測,但很容易嘗試,直到有人提出真正的答案。 :-) – blm
'actionPerformed(...)'在UI線程中被調用,並且你正在調用'Thread.sleep(...)'來阻止它。直到'actionPerformed(...)'返回,用戶界面才能更新。 –
好的,我瘋狂的猜測是錯誤的,對不起。凱文的評論和羅勒的回答對我來說很有意義(我有點懊惱,我沒有想到它,但是自從我做AWT/Swing的東西以來已經有一段時間了。) – blm