Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

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

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)

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...