简体   繁体   English

Java thread.sleep也使ui进入睡眠状态

[英]java thread.sleep puts swing ui to sleep too

I im creating a simple testing app that runs a check every hour on the selected directory/s using thread.sleep() through JFileChooser. 我正在创建一个简单的测试应用程序,该应用程序通过JFileChooser使用thread.sleep()在选定目录上每小时运行一次检查。 But when i select the directory and the method runs the ui panel goes grey and the swing bits disappear. 但是,当我选择目录并运行该方法时,ui面板变为灰色,摆动位消失。 The thread seems to be putting the ui to sleep as well as the method its calling. 线程似乎正在使ui及其调用的方法进入睡眠状态。

if (option == JFileChooser.APPROVE_OPTION) {
    selectedDirectory = chooser.getSelectedFiles();
    try {
        while (true) {
            runCheck(selectedDirectory);
            Thread.sleep(1000*5);//1000 is 1 second
        }
    } catch (InterruptedException e1) {
        Thread.currentThread().interrupt();
        e1.printStackTrace();
    }               
} 

Im looking for a way around this issue so that i can print the results of the checks being run in the ui .setText(result) 我正在寻找解决此问题的方法,以便我可以打印在ui .setText(result)中运行的检查结果

You are correct about the code putting the UI to sleep. 您对使UI处于休眠状态的代码是正确的。 Since sleep is called on the Event Dispatch Thread (the thread responsible for running the gui) the UI stops processing events and 'goes to sleep'. 由于sleep是在事件调度线程(负责运行gui的线程)上调用的,因此UI会停止处理事件并“进入睡眠状态”。

I think what you want is a javax.swing.Timer . 我认为您想要的是javax.swing.Timer

Timer t = new Timer(1000 * 5, new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // do your reoccuring task
    }
});

This will cause your reoccurring task to be performed off of the EDT, and thus it wont leave your ui unresponsive. 这将导致您的重复任务在EDT之外执行,因此不会使ui失去响应。

If the code you have posted runs on the EventDispatchThread, then there is no way Swing can redraw the GUI. 如果您发布的代码在EventDispatchThread上运行,则Swing无法重绘GUI。 You're blocking (sleeping in) the thread that's supposed to handle that! 您正在阻塞(休眠)应该处理该线程的线程!

This is because you are running you check in the main GUI thread and are using an infinite loop. 这是因为您在运行时签入了主GUI线程,并且正在使用无限循环。 This check is a background task and should be executed in it's own thread so that the GUI can still receive and react to input by the user. 此检查是一项后台任务,应在其自己的线程中执行,以便GUI仍可以接收用户的输入并对输入作出反应。

You also do not need to write your own implementation, Java has a Timer object. 您也不需要编写自己的实现,Java有一个Timer对象。

Edit: There is also a Swing specific Timer object. 编辑:还有一个特定于Swing的Timer对象。 This will have the action occur in the GUI thread, so if your task is long, it can cause the GUI to still lock up while the action is occurring (but not while it is waiting). 这将使操作在GUI线程中发生,因此,如果您的任务很长,则可能导致GUI在执行操作时(而不是在等待时)仍然锁定。

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

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