简体   繁体   中英

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? .

My question is: During the execution of this code, does it hangs the whole JFrame . For eg- I have placed a JTextField on my form (win1), And I want some random input from user. Will the JForm will be able to accept input during this time frame? Thanks.

Yes it waits until doStuf() finishes it's job and calls it again. 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. but because Timer class creates a new Thread then does not block your JFrame. In other words, the JFrame control and the new Timer control run over two separate thread.

It is good to test your program yourself and see the behavior...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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