First Program in Java Swing

In this example, we are going to use the Swing library to create a simple graphical user interface (GUI) application to write the first program in Java Swing. The program creates a JFrame (window) and a JLabel (text label), and adds the label to the frame. The frame is then sized, and we will set it to close the application when the user closes the frame. Finally, we make the frame visible to the user.

You’ll need to have Java and a development environment set up to compile and run this code. Make sure to import the necessary libraries, which are part of the Java Standard Library.

import javax.swing.JFrame;
import javax.swing.JLabel;

public class HelloWorldSwing {
	public static void main(String[] args) {
		JFrame frame = new JFrame("Hello World Swing");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(300, 300);

		JLabel label = new JLabel("Hello, World!");
		frame.getContentPane().add(label);

		frame.setVisible(true);

	}
}

Output:

First Program in Swing Java

Sharing Is Caring: