你如何将thread.sleep转换为javax.swing.timer?

时间:2014-01-12 22:19:42

标签: java multithreading swing user-interface timer

有没有办法轻松将thread.sleep转换为javax.swing.timer?

我需要这样做的原因是当你按下按钮时停止用户界面冻结,这样你就可以实现一个暂停按钮。

代码示例:

btnStartTiming.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent arg0) {
                try{
                         inputA = Double.parseDouble(txtEnterHowLong.getText()); //Changes double to string and receives input from user
                        }catch(NumberFormatException ex){                        
                        }

            while (counter <= inputA){
                    txtCounter.setText(counter + ""); 
                    try {
                        Thread.sleep(1000);
                    } catch(InterruptedException ex) {
                        Thread.currentThread().interrupt();   
                    }
                    System.out.println(counter);
                    counter++;
                    }
        }
    });

2 个答案:

答案 0 :(得分:3)

一些提示:

答案 1 :(得分:2)

  • java.swing.Timer放入构造函数中。您可以使用按钮.start()计时器。
  • 也可以在计时器代码中添加if语句而不是while,而不是.stop()

像这样的东西

int delay = 1000;
Timer timer = new Timer(delay, null);

public Constructor(){
    timer = new Timer(delay, new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            if (counter >= inputA) {
                timer.stop();
            } else {

                // do something
            }
        }
    });
    button.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            timer.start();
        }
    });

}