Thursday, December 24, 2009

Swing Invokelater Example

Here we can see How to write a responsive User interfaces using Swing.
Most post-initialization GUI work naturally occurs in the event-dispatching thread. Once the GUI is visible, most programs are driven by events such as button actions or mouse clicks, which are always handled in the event-dispatching thread. A program that uses separate worker threads to perform GUI-related processing can use invokelater and invokeandwait methods to cause a Runnable object to be run on the event-dispatching thread. 
These methods were originally provided in the SwingUtilities class.
  • invokeLater requests that some code be executed in the event-dispatching thread. This method returns immediately, without waiting for the code to execute.
  • invokeandwait acts like invokeLater , except that it waits for the code to execute. Generally, you should use invokeLater instead.
invokeLater Method
You can call invokeLater from any thread to request the event-dispatching thread to run certain code. You must put this code in the run method of a Runnable object and specify the Runnable object as the argument to invokeLater . The invokeLater method returns immediately, it doesn't wait for the event- dispatching thread to execute the code.
Runnable doWork = new Runnable() { 
public void run() { 
// GUI Work here 
The invokeandwait method is just like the invokeLater method, except that invokeandwait doesn't return until the event-dispatching thread has executed the specified code. Whenever possible, you should use invokeLater instead of invokeandwait . If you use invokeandwait , make sure that the thread that calls invokeandwait does not hold any locks that other threads might need while the invoked code is running. 
below shows how a thread that needs access to GUI state, such as the contents of a pair of JTextFields, can use  invokeandwait to access the necessary information. 
void showHelloThereDialog() throws Exception {
Runnable doShowModalDialog = new Runnable() {
public void run() {
void printTextField() throws Exception {
    final String[] myStrings = new String[2];
    Runnable doGetTextFieldText = new Runnable() {
        public void run() {        
            myStrings[0] = textField0.getText();
            myStrings[1] = textField1.getText();
    System.out.println(myStrings[0] + " " + myStrings[1]);
Using invokeAndWaitto access GUI state
Remember that you only need to use these methods if you want to update the GUI from a worker thread that you created. If you haven't created any threads, then you don't need to use invokeLater or invokeandwait.


Post a Comment

The Link Exchange - Your ultimate resource for link exchange!

About This Blog

  © Blogger template Webnolia by 2009

Back to TOP