Developing the First Swing Application

Summary: in this tutorial, we are going to show you step by step developing the first Java Swing application that displays a basic window on the desktop.

The following illustrates the first Swing application’s source code. You just need to copy the source code, paste it into your Java IDE and execute it. It is noticed that the file name should be

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: JavaScript (javascript)

Here is the output of the application:

Developing the first Swing 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 window’s width and height. In this case, it sets the window 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.


In the main() method, we created an instance of the Main class and showed the window by calling the method setVisible() to set 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.