Java SwingUtilities invoke and wait

Description

Java SwingUtilities invoke and wait

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);
   }//from w  ww.  j a v a2s. co m

   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