Reputation: 4609
I have a Window Listener on the main JFrame of my application. I also have a button listener on a button within the application. I used this as the pattern for the button listener:
good.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
// We're going to do something that takes a long time, so we
// spin off a thread and update the display when we're done.
Thread worker = new Thread() {
public void run() {
// Report the result using invokeLater().
SwingUtilities.invokeLater(new Runnable() {
public void run() {
for(int i=0; i<1000000; i++){
System.out.println("foo");
}
}
});
}
};
worker.start(); // So we don't hold up the dispatch thread.
}
});
When I click on the button, I see the printout for each iteration, but the window listener is not triggered until after the loop has finished executing. The print 'foo' is just there to simulate something that takes a while, and I want the listener to be triggered as soon as the window event occurs (which could be somewhere in the middle of the run() method execution), but it seems like it's not being triggered until the end of the for loop.
Any idea why?
Upvotes: 0
Views: 141
Reputation: 347184
So, all this...
// Report the result using invokeLater().
SwingUtilities.invokeLater(new Runnable() {
public void run() {
for(int i=0; i<1000000; i++){
System.out.println("foo");
}
}
});
Will do is, is cause the loop to be executed within the context of the Event Dispatching Thread, which will prevent the EDT from processing the event queue, including paint request.
In your case, it might be easier to use a SwingWorker
which you can use to publish
/process
information from the background thread to the EDT as well as supports progress notification
See How to use SwingWorker for more details
Upvotes: 2
Reputation: 8348
Swing is single-threaded - the Event Dispatch Thread (EDT) manages painting and events for Swing. Any long running tasks placed on the EDT will prevent the EDT from doings tasks until the long running task is complete (in other words, the UI will seem like it has locked up). Here, your code dispatches the long running process (the for
loop) onto the EDT using SwingUtilities
- if you have a long running task and want a responsive Swing UI during the process, then place your long running task into it's own Thread, or use a SwingWorker.
Upvotes: 3