java thread.sleep 也让 Swing ui 进入睡眠状态 [英] java thread.sleep puts swing ui to sleep too

查看:33
本文介绍了java thread.sleep 也让 Swing ui 进入睡眠状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个简单的测试应用程序,它使用 thread.sleep() 通过 JFileChooser 每小时对所选目录运行一次检查.但是当我选择目录并且方法运行时,ui 面板变灰并且摆动位消失.该线程似乎使 ui 及其调用的方法进入睡眠状态.

I im creating a simple testing app that runs a check every hour on the selected directory/s using thread.sleep() through JFileChooser. But when i select the directory and the method runs the ui panel goes grey and the swing bits disappear. The thread seems to be putting the ui to sleep as well as the method its calling.

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();
    }               
} 

我正在寻找解决此问题的方法,以便我可以打印在 ui .setText(result) 中运行的检查结果

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 进入休眠状态的代码是正确的.由于在事件调度线程(负责运行 gui 的线程)上调用 sleep,因此 UI 停止处理事件并进入睡眠".

You are correct about the code putting the UI to sleep. 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'.

我认为你想要的是一个 javax.swing.Timer.

I think what you want is a javax.swing.Timer.

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

这将导致您的重复任务在 EDT 之外执行,因此不会让您的用户界面无响应.

This will cause your reoccurring task to be performed off of the EDT, and thus it wont leave your ui unresponsive.

这篇关于java thread.sleep 也让 Swing ui 进入睡眠状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆