简体   繁体   English

计时器类。 接受用户输入而不挂JForm

[英]Timer Class. Accepting Input from user without hanging the JForm

Have a look at this piece of code: 看一下这段代码:

public class TestClass {
    public long myLong = 1234;

    public static void main(String[] args) {
        final TestClass test = new TestClass();

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                test.doStuff();
            }
        }, 0, test.myLong);
    }

    public void doStuff(){
        //do stuff here
    }
}

/Originally copied from How to use Timer class to call a method, do something, reset timer, repeat? /最初从如何使用Timer类调用方法,执行某些操作,重置计时器,重复执行? .

My question is: During the execution of this code, does it hangs the whole JFrame . 我的问题是:在执行此代码期间,它是否会挂起整个JFrame For eg- I have placed a JTextField on my form (win1), And I want some random input from user. 例如,我在表单(win1)上放置了一个JTextField ,并且我希望用户输入一些随机信息。 Will the JForm will be able to accept input during this time frame? JForm将能够在此时间范围内接受输入吗? Thanks. 谢谢。

Yes it waits until doStuf() finishes it's job and calls it again. 是的,它一直等到doStuf()完成工作并再次调用它。 Test it with this: 用这个测试:

    static void doStuf() {
        Scanner rowInput = new Scanner(System.in);
        System.out.print("Enter: ");
        String row = rowInput.next();
        System.out.println(row);
    }

It depends on how you build and run the JFrame. 这取决于您如何构建和运行JFrame。 but because Timer class creates a new Thread then does not block your JFrame. 但是由于Timer类创建了一个新线程,因此不会阻止您的JFrame。 In other words, the JFrame control and the new Timer control run over two separate thread. 换句话说,JFrame控件和新的Timer控件在两个单独的线程上运行。

It is good to test your program yourself and see the behavior... 最好自己测试程序并查看行为...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM