在Swing中遇到Thread.sleep的问题

时间:2015-10-03 07:03:06

标签: java swing event-dispatch-thread thread-sleep

这个程序被编写为0到1000之间的数字,但它直接进入1000而不显示计数过程。我使用进度条和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();
    }
}

1 个答案:

答案 0 :(得分:3)

任何长时间运行的任务都应该在一个单独的线程中运行。你使用Thread.sleep肯定有资格作为长期运行。

通过在Swing用户界面线程中运行,在代码完成之前,不能在该用户界面中呈现更新。相反,你的计数应该在另一个线程中产生。其他线程应使用SwingWorker以线程安全的方式定期更新用户界面。

研究launching threadsexecutors,例如ScheduledExecutorService,Swing event-dispatch thread(EDT)和SwingWorker。

Swing Timer

更简单的方法可能是Swing Timer classTutorial),不要与java.util.Timer混淆。它将为您完成大部分线程处理工作。但我没有经验。

相关问题