用户输入使用线程倒计时

时间:2018-03-20 10:51:37

标签: java multithreading

我有一个由1个按钮,1个文本字段,1个标签组成的GUI。它 从文本字段将字符串转换为int。将其减1.印在标签上

 @Override
    public void run() {
        while (runner == Thread.currentThread()) {
            try {
                System.out.println("Step 1");
                int count = Integer.valueOf(txt.getText());
                System.out.println("Step 2");
                while (count != 0) {
                    count--;
                    lblcount.setText("Time Left is " + Integer.toString(count));
                    Thread.sleep(1000);
                    System.out.println("Step 3");
                }
            } catch (InterruptedException ie) {
                System.out.println("error of some sort here step 4");
            }
        }
        repaint();
    }

    public static void main(String[] args) {
        Timed2 dd = new Timed2();
    }

    @Override
    public void actionPerformed(ActionEvent eve) {
        Object source = eve.getSource();
        if (source.equals(btncount)) {
            run();
        }
    } 

控制台错误

Step 1
Exception in thread "Thread-1" java.lang.NumberFormatException: 
For input string: ""
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

    at java.lang.Integer.parseInt(Integer.java:504)

    at java.lang.Integer.valueOf(Integer.java:582)

    at timed2.Timed2.run(Timed2.java:42)

    at java.lang.Thread.run(Thread.java:745)

如何在用户输入数字之后更改线程以读取文本框,而不是之前给我这个错误,这意味着它不会倒计时

1 个答案:

答案 0 :(得分:0)

此外,它似乎无法解析空字符串

 For input string: ""
    at 
 java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

因此,如果从GUI发送任何值,可以检查调试。