java thread.sleep也让swing ui入睡 [英] java thread.sleep puts swing ui to sleep too

查看:87
本文介绍了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(结果)中运行的检查结果

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)

推荐答案

你对正确的代码是正确的用户界面睡觉。由于在事件调度线程(负责运行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执行,因此它不会离开你的ui没有反应。

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天全站免登陆