Creating Your First Java Swing Application: Building a Simple JFrame

JFrame:

  • JFrame is an essential component in java swing.

  • It is a part of SWT(Standard widget toolkit).

  • JFrame allows the users to create a top level window which serves as the main window for GUI based java applications and provides a way to access platform independent graphical interfaces.

  • JFrame is a part of javax.swing package.

Constructors in JFrame:

• JFrame(): It creates a new Frame with no title

• JFrame(String Title): it creates a new Frame with the Title.

• JFrame(GraphicsConfiguration gc, String title): It creates a new JFrame with the given Graphics configuration and given title.

• JFrame(Rectangle r): It creates a Frame with specified bounds.

• JFrame(Rectangle r, String title): Creates a frame with specified bounds and given title

Methods in JFrame:

• add(Component c): Adds a component to the JFrame.

• remove(Component c): Removes a component from JFrame:

• setTitle(String title): Sets the title to the JFrame.

• setSize(int width, int height): sets Layout height and width of JFrame.

• setIconImage(Image image): sets icon image for the JFrame.

Program:

// Sample program to create a JFrame.

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

class MyFrame {
    public static void main(String[] args) {
        JFrame myFrame = new JFrame("My first JFrame");
        JLabel myLabel = new JLabel("Hello Sai Sahith");
        myFrame.add(myLabel);
        myFrame.setSize(300, 200);
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setVisible(true);
    }
}
0
Subscribe to my newsletter

Read articles from Sai Sahith Polimera directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sai Sahith Polimera
Sai Sahith Polimera