import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Hello World!");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(200, 100);
frame.setVisible(true);
});
}
}
Inside the main
method:
On the first line SwingUtilities.invokeLater
is called and a lambda expression with a block of code () -> {...}
is passed to it. This executes the passed lambda expression on the EDT, which is short for Event Dispatch Thread, instead of the main thread. This is necessary, because inside the lambda expression's code block, there are Swing components going to be created and updated.
Inside the code block of the lambda expression:
On the first line, a new JFrame
instance called frame
is created using new JFrame("Hello World!")
. This creates a window instance with "Hello World!" on its title. Afterwards on the second line the frame
is configured to EXIT_ON_CLOSE
. Otherwise the window will just be closed, but the execution of the program is going to remain active. The third line configures the frame
instance to be 200 pixels in width and 100 pixels in height using the setSize
method. Until now the execution won't show up anything at all. Only after calling setVisible(true)
on the fourth line, the frame
instance is configured to appear on the screen.