How to write lambda expression code for SwingUtilities.invokeLater in Java?

Java 8Object Oriented ProgrammingProgramming

An event handling code that runs on a special thread called event dispatch thread(EDT). Most of the code that invokes swing methods also runs on this EDT thread. It is necessary because most of swing object methods do not thread-safe. SwingUtilities is a utility class and has one important static method, invokeLater(). This method can be used to perform a task asynchronously in the AWT event dispatcher thread.

Syntax

public static void invokeLater(Runnable doRun)

Example

import javax.swing.*;

public class InvokeLAterLambdaTest {
   public static void main(String[] args) {
      SwingUtilities.invokeLater(() -> {    // lambda expression code 
         JFrame frame = new JFrame();
         frame.setTitle("InvokeLater Lambda Test");
         frame.getContentPane().add(new JLabel("Welcome to Tutorials Point", SwingConstants.CENTER));
         frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
         frame.setSize(375, 250);
         frame.setLocationRelativeTo(null);
         frame.setVisible(true);
      });  // end of lambda
   }
}

Output

raja
Published on 10-Jan-2020 12:21:30
Advertisements