Java SwingUtilities is event dispatch event

Description

Java SwingUtilities is event dispatch event

import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Main {

   public static void processOnSwingEventThread(Runnable todo) {
      processOnSwingEventThread(todo, false);
   }//w  ww. j a v  a 2 s.  c om

   public static void processOnSwingEventThread(Runnable todo, boolean wait) {
      if (todo == null) {
         throw new IllegalArgumentException("Runnable == null");
      }

      if (wait) {
         if (SwingUtilities.isEventDispatchThread()) {
            todo.run();
         } else {
            try {
               SwingUtilities.invokeAndWait(todo);
            } catch (Exception ex) {
               throw new RuntimeException(ex);
            }
         }
      } else {
         if (SwingUtilities.isEventDispatchThread()) {
            todo.run();
         } else {
            SwingUtilities.invokeLater(todo);
         }
      }
   }

   public static void main(String[] args) throws Exception {
      JFrame frame = new JFrame("");
      JButton button = new JButton("OK");

      button.addActionListener(e -> {
         processOnSwingEventThread(() -> {
            System.out.println("hi");
         }, true);
      });

      frame.add(button, BorderLayout.NORTH);
      frame.pack();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }

}



PreviousNext

Related