简体   繁体   English

如何限制用户在一定时间内与程序交互?

[英]How to restrict the user from interacting with the program for a certain period of time?

I'm trying to restrict the user from interacting with the program for a certain period of time, but sadly, with no success.我试图限制用户在一段时间内与程序交互,但遗憾的是,没有成功。 I've tried using Thread.sleep , but as soon as the sleep action ends, the users' input catches up and keeps executing until it's finished.我试过使用Thread.sleep ,但是一旦sleep操作结束,用户的输入就会赶上并继续执行,直到它完成。

For example, if I use the code below, the program will act as mentioned above: it'll sleep for the provided period of time (1,5s) and then the users' actions will catch up (it'll print "After waiting" as much times as the user clicked while the Thread.sleep was active).例如,如果我使用下面的代码,程序将按照上面提到的方式运行:它会在提供的时间段(1,5s)内休眠,然后用户的操作会赶上(它会打印“等待后"与用户在Thread.sleep处于活动状态时单击的次数一样多)。 So how would I prevent this?那么我将如何防止这种情况发生? Any suggestions would be greatly appreciated.任何建议将不胜感激。

public void mouseClicked(MouseEvent e) {
        print();
    }

public void print() {
    System.out.println("After waiting.");
    try {
        Thread.sleep(1500);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

The reason is that Thread.sleep() will block the UI Thread.原因是Thread.sleep()会阻塞 UI 线程。 So by clicking the first time, you will get an output and your application will store the following events from clicking again during the time for sleeping.因此,通过第一次单击,您将获得一个输出,并且您的应用程序将存储以下事件,以便在睡眠期间再次单击。 Then, after your GUI-Thread comes back from sleeping, the events are released and some of the print-prompts are executed until it sleeps.然后,在您的 GUI 线程从睡眠状态恢复后,事件将被释放并执行一些打印提示,直到它进入睡眠状态。 Because因为

It is not very trivial to block the UI-Thread.阻塞 UI-Thread 并不是一件小事。 If you want to prevent user input, you should disable the button or the Node in general which fires the event and enable it if its processing was finished.如果您想阻止用户输入,您应该禁用触发事件的按钮或节点,并在处理完成后启用它。

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

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