Summary: in this tutorial, you’ll learn how to develop the first Java Swing application that displays a basic window on the desktop.
The following illustrates the first Swing application’s source code. You need to copy the source code, paste it into your Java IDE and execute it. It is noticed that the file name should be Main.java.
package swingdemo1;
import javax.swing.JFrame;
public class Main extends JFrame{
public Main(){
setSize(400, 300);
setTitle("Developing the First Swing Application");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Main demo = new Main( );
demo.setVisible(true);
}
}
Code language: Java (java)
Here is the output of the application:
Let’s examine the source code above in a greater detail:
- First, we imported JFrame widget which comes from the package javax.swing.
- Second, we created Main class inheriting from the JFrame class.
- Third, we called various methods of JFrame class to display a window.
setSize(400, 300);
The setSize() method is used to set the window’s width and height. In this case, it sets the window to 400px in width and 300px in height.
setTitle("Developing the First Swing Application");
Code language: JavaScript (javascript)
The setTitle() is used to set the title of the window. As you see, the window’s title, in this case, is “Developing the First Swing Application”.
The method setDefaultCloseOperation() is used to configure what happens when the window is closed. In this case, by default it does nothing.
setDefaultCloseOperation(EXIT_ON_CLOSE);
In the main() method, we created an instance of the Main class and showed the window by calling the method setVisible() to set the visible of the window to the Boolean value of true.
The first application is a basic framework for working with other Java swing components in the next tutorials, making sure you understand and get familiar with it.