Java Swing Example Program Hello World and steps to run

By | August 16, 2011

Java Swing is very important to develop graphical user interface (GUI) window based program with Java. You can find here Java Swing sample program and steps to run it. The following program will help you to undersand and Java Swing Program.

Step 1:
Import the required Swing and AWT package as follows
import javax.swing.*;
import java.awt.*;

Step 2:
Create a class which extends JFrame. JFrame is a component which help you to create a Frame window to perform all your operation using GUI.

Example Program:
import javax.swing.*;
import java.awt.*;
public class HelloSwing extends JFrame{
JFrame frame1;
JLabel l1; //It will create a label to diplay some name in inside the window.
public HelloSwing(){
frame1=new JFrame();
Container cp=frame1.getContentPane(); //which help you to display components in window.
cp.setLayout(null);
l1=new JLabel(“Hello Java Swing..”); // setting custom message and this will appear in inside window.
l1.setBounds(70,30,180,30);
cp.add(l1);
frame1.setSize(300,200);
frame1.setVisible(true);
}

public static void main(String[] args) {
// TODO Auto-generated method stub
new HelloSwing();
}
}

Once you type the above program save this with classname.java (ex : HelloSwing.java). Then compile the program and run as follows

javac HelloSwing.java (Press Enter)
java HelloSwing (Press Enter)
You will get the Frame window with “Hello Java Swing” message in that window.

Leave a Reply

Your email address will not be published. Required fields are marked *