I have application with:
- one JTextField for user input,
- one JLabel fro showing busy status,
- one JTextArea for printing results of search.
I want user to write text to textfield, press enter and see results. I have listener like this:
private void searchForPattern(java.awt.event.ActionEvent evt) {
textArea.setText("");
busyLabel.setText("Searchnig ...");
doSearch();
busyLabel.setText("Idle");
}
In doSearch there is quite complicated algorithm that opens lots of XML files and searches for given pattern, it takes a while. Text of busyLabel is changed to Searching … only after doSearch completed. There is no second thread in doSearch, only lot of IO operations.
How can I fix this?
You’ve got a classic Swing concurrency issue (tutorial: Concurrency in Swing) where doSearch is tying up the Swing event thread. Since this thread is where Swing does all of its painting/drawing and interacting with users, if it gets tied up by code that takes any perceptible amount of time to complete, the whole application “freezes” with no components getting updated and all user interactions getting ignored.
Solution: do it on a background thread such as that provided by a SwingWorker object. Set the “Idle” String into the JLabel in the SwingWorker’s
done()method.i.e.,