What is the importance of SwingUtilities class in Java?


In Java, after swing components displayed on the screen, they can be operated by only one thread called Event Handling Thread. We can write our code in a separate block and can give this block reference to Event Handling thread. The SwingUtilities class has two important static methods, invokeAndWait() and invokeLater() to use to put references to blocks of code onto the event queue.

Syntax

public static void invokeAndWait(Runnable doRun) throws InterruptedException, InvocationTargetException
public static void invokeLater(Runnable doRun)

The parameter doRun is a reference to an instance of Runnable interface. In this case, the Runnable interface will not be passed to the constructor of a Thread. The Runnable interface is simply being used as a means to identify the entry point for the event thread. Just as a newly spawned thread will invoke run(), the event thread will invoke run() method when it has processed all the other events pending in the queue. An InterruptedException is thrown if the thread that called invokeAndWait() or invokeLater() is interrupted before the block of code referred to by target completes. An InvocationTargetException is thrown if an uncaught exception is thrown by the code inside the run() method.

Example

import javax.swing.*;
import java.lang.reflect.InvocationTargetException;
public class SwingUtilitiesTest {
   public static void main(String[] args) {
      final JButton button = new JButton("Not Changed");
      JPanel panel = new JPanel();
      panel.add(button);
      JFrame f = new JFrame("InvokeAndWaitMain");
      f.setContentPane(panel);
      f.setSize(300, 100);
      f.setVisible(true);
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      System.out.println(Thread.currentThread().getName()+" is going into sleep for 3 seconds");
      try {
         Thread.sleep(3000);
      } catch(Exception e){ }
      //Preparing code for label change
      Runnable r = new Runnable() {
         @Override
         public void run() {
            System.out.println(Thread.currentThread().getName()+"is going into sleep for 10 seconds");
            try {
               Thread.sleep(10000);
            } catch(Exception e){ }
          button.setText("Button Text Changed by "+ Thread.currentThread().getName());
          System.out.println("Button changes ended");
      }
    };
      System.out.println("Component changes put on the event thread by main thread");
          try {
            SwingUtilities.invokeAndWait(r);
         } catch (InvocationTargetException | InterruptedException e) {
            e.printStackTrace();
         }
      System.out.println("Main thread reached end");
   }
}

Output

                                                         


raja
raja

e

Updated on: 07-Feb-2020

936 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements