BCA / B.Tech 9 min read

What is Java Swing and its methods

What is Java Swing?

Java Swing is a part of the Java Foundation Classes (JFC) used to create window-based applications.

It is built on top of the AWT (Abstract Windowing Toolkit) API and is written entirely in Java.

Use of Java Swing

The Swing API is used by developers to create Java-based Front End/GUI applications. The Swing API is used as a substitute for the AWT API.

In Java, the Javax.swing package provides classes for the Swing API such as:

  • JButton
  • JComboBox
  • JList
  • JTabbedPane
  • JToolbar
  • JTextArea
  • JRadioButton
  • JPasswordField

Properties of Java Swing

1. Platform Independent

Swing components are platform-independent, meaning they can run on any operating system.

2. Light Weight

Since Swing components are written entirely in Java, they are light weight.

3. Controls

Swing has many good controls like:

  • Tree
  • TabbedPane
  • Slider
  • ColorPicker
  • Table Controls

4. Customize

We can easily customize Swing controls.

5. Look and Feel

The look and feel of a Swing-based application can also be changed at runtime.

Methods of Java Swing Components Classes

MethodDescription
public void add(Component c)It is used to add one component to another component.
public void setSize(int width, int height)It is used to set the size of the component.
public void setLayout(LayoutManager m)It is used to set the Layout Manager for the component.
public void setVisible(boolean b)It is used to set the visibility of the component.

A Simple Program of Java Swing


import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class App {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame("Hello World Swing!");
                frame.setSize(500, 400);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

In this article, we learned what Java Swing is, its properties, and its various methods. Hope this information proves useful for you.