Home Java javaTutorial Creating Java GUIs with Swing Components

Creating Java GUIs with Swing Components

Jan 08, 2025 am 10:09 AM

This article explores Java’s Swing toolkit. A library for building Graphical User Interfaces (GUIs) using components like JFrame, JDialog, and JApplet, which serve as essential top-level containers. It also demonstrates how to create a simple contact form using Swing components.


Swing is a Java library used to create simple Graphical User Interfaces (GUIs). It is a GUI widget toolkit providing a collection of components for constructing GUIs. (Oracle Docs, n.d.a). Swing components are written entirely in the Java programming language. There are three generally useful top-level container classes: JFrame, JDialog, and JApplet (Oracle Docs, n.d. b).

Top-level container:

A JFrame is a top-level window with a title and a border.

Creating Java GUIs with Swing Components
(Oracle Docs, n.d.b, How to Make Frames (Main Windows).

A JDialog window is an independent sub-window that temporaries notice apart from the main Swing Application Window.
Creating Java GUIs with Swing Components
(Oracle Docs, n.d.b, How to Make Dialogs)

JApplet, a Java applet is a special kind of Java program that a browser enabled with Java technology can download from the internet and run. An applet is typically embedded inside a web page and runs in the context of a browser. An applet must be a subclass of the applet. Applet class. The Applet class provides the standard interface between the applet and the browser environment” (Oracle Docs, n.d.c).
Every program that utilizes Swing components includes at least one top-level container. This top-level container serves as the root of a containment hierarchy, which encompasses all the Swing components within the container (Oracle Docs, n.d.b).

Typically, a standalone application with a Swing-based GUI will have at least one containment hierarchy with a JFrame as the root. For instance, if an application features a main window and two dialogs, it will have three containment hierarchies, each with its own top-level container. The main window will have a JFrame as its root, while each dialog will have a JDialog as its root.A Swing-based applet also has at least one containment hierarchy, with one rooted by a JApplet object. For example, an applet that displays a dialog will have two containment hierarchies. The components within the browser window belong to a containment hierarchy rooted by a JApplet object, while the dialog belongs to a containment hierarchy rooted by a JDialog object.

JComponent Class:

Except for top-level containers, all Swing components that start with “J” are derived from the JComponent class. For instance, JPanel, JScrollPane, JButton, and JTable all inherit from JComponent. However, JFrame and JDialog do not, as they are top-level containers (Oracle Docs, n.d.b, The JComponent Class)

Differences between Frame and Panel:

Frame:
A JFrame is a top-level container that represents a window with a title, borders, and buttons.
It is typically used as the main window of an application.
A JFrame can contain multiple components, including JPanel, JScrollPane, JButton, JTable, and etc.

Panel:
A JPanel is a generic container that is used to group a set of components together within a window.
It does not have window decorations like a title bar or close button.
A JPanel is often used to organize and manage layout within a JFrame.

Every program that utilizes Swing components includes at least one top-level container. This top-level container serves as the root of a containment hierarchy, which encompasses all the Swing components within the container (Oracle Docs, n.d.b).

Typically, a standalone application with a Swing-based GUI will have at least one containment hierarchy with a JFrame as the root. For instance, if an application features a main window and two dialogs, it will have three containment hierarchies, each with its own top-level container. The main window will have a JFrame as its root, while each dialog will have a JDialog as its root.

A Swing-based applet also has at least one containment hierarchy, with one rooted by a JApplet object. For example, an applet that displays a dialog will have two containment hierarchies. The components within the browser window belong to a containment hierarchy rooted by a JApplet object, while the dialog belongs to a containment hierarchy rooted by a JDialog object.

The example below includes a JFrame and a JPanel, as well as additional components like buttons, text fields, and labels using a GridBagLayout. Moreover, it also displays a message using JDialog, the JOptionPane component, and a Dialog window component. It is a simple graphical user interface (GUI) contact form using Swing components.

//--- Abstract Window Toolkit (AWT)

// Provides layout manager for arranging components in five regions: 
// north, south, east, west, and center.
import java.awt.BorderLayout;
// Grid layout - Specifies constraints for components that are laid out using the GridBagLayout.
import java.awt.GridBagConstraints;
// Grid - layout manager that aligns components vertically and horizontally, 
// without requiring the components to be of the same size.
import java.awt.GridBagLayout;
// Gird padding - Specifies the space (padding) between components and their borders.
import java.awt.Insets;
// Button - Provides the capability to handle action events like button clicks.
import java.awt.event.ActionEvent;
// Button event - Allows handling of action events, such as button clicks.
import java.awt.event.ActionListener;

//--- swing GUI

// Button - Provides a button component that can trigger actions when clicked.
import javax.swing.JButton;
// Frame - Provides a window with decorations 
// such as a title, border, and buttons for closing and minimizing.
import javax.swing.JFrame;
// Labels - Provides a display area for a short text string or an image, or both.
import javax.swing.JLabel;
// Submition Message - Provides standard dialog boxes such as message, input, and confirmation dialogs.
import javax.swing.JOptionPane;
// Panel - Provides a generic container for grouping components together.
import javax.swing.JPanel;
// Scroll user message - Provides to the a scrollable view of a lightweight component.
import javax.swing.JScrollPane;
// User message - Provides a multi-line area to display/edit plain text.
import javax.swing.JTextArea;
// Name & Email - Provides a single-line text field for user input.
import javax.swing.JTextField;

/**
 * This class generates a simple contact form. The form includes fields for the
 * user's name, email, and message, and a submit button to submit the form.
 * 
 * @author Alejandro Ricciardi
 * @version 1.0
 * @date 06/16/2024
 */
public class contactForm {
    /**
     * The main method to create and display the contact form.
     *
     * @param args Command line arguments
     */
    public static void main(String[] args) {

        /*------------
         |   Frame   |
         ------------*/

        // ---- Initializes frame
        // Creates the main application frame
        JFrame frame = new JFrame("Contact Form");
        frame.setSize(400, 300); // Set the size of the frame
                // Close the application when the frame is closed
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        frame.setLayout(new BorderLayout()); // Use BorderLayout for the frame

        /*------------
         |   Panel   |
         ------------*/

        // ---- Initializes panel
        // Create a panel with GridBagLayout
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gridForm = new GridBagConstraints();
        gridForm.insets = new Insets(5, 5, 5, 5); // Add padding around components

        // ---- Creates and adds grid components to the panel       // -- Name
        // Adds "Name" label
        JLabel nameLabel = new JLabel("Name:");
        gridForm.gridx = 0; // Position at column 0
        gridForm.gridy = 0; // Position at row 0
        panel.add(nameLabel, gridForm);
        // Add text field for name input
        JTextField nameField = new JTextField(20);
        gridForm.gridx = 1; // Position at column 1
        gridForm.gridy = 0; // Position at row 0
        panel.add(nameField, gridForm);

        // -- Email
        // Add "Email" label
        JLabel emailLabel = new JLabel("Email:");
        gridForm.gridx = 0; // Position at column 0
        gridForm.gridy = 1; // Position at row 1
        panel.add(emailLabel, gridForm);
        // Adds text field for email input
        JTextField emailField = new JTextField(20);
        gridForm.gridx = 1; // Position at column 1
        gridForm.gridy = 1; // Position at row 1
        panel.add(emailField, gridForm);

        // Adds "Message" label
        JLabel messageLabel = new JLabel("Message:");
        gridForm.gridx = 0; // Position at column 0
        gridForm.gridy = 2; // Position at row 2
        panel.add(messageLabel, gridForm);

        // -- Message
        // Adds text area for message input with a scroll pane
        JTextArea messageArea = new JTextArea(5, 20);
        JScrollPane scrollPane = new JScrollPane(messageArea);
        gridForm.gridx = 1; // Position at column 1
        gridForm.gridy = 2; // Position at row 2
        panel.add(scrollPane, gridForm);
        // Adds "Submit" button
        JButton submitButton = new JButton("Submit");
        gridForm.gridx = 1; // Position at column 1
        gridForm.gridy = 3; // Position at row 3
        panel.add(submitButton, gridForm);

        // Adds the panel to the frame's center
        frame.add(panel, BorderLayout.CENTER);

        // Make the frame visible
        frame.setVisible(true);

        /*------------
         |  JDialog  |
         ------------*/
        // Add action listener to the submit button
        ActionListener submitBtnClicked = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Display a message dialog when the submit button is clicked
                JOptionPane.showMessageDialog(frame, "Message was sent!");
            }
        };

        submitButton.addActionListener(submitBtnClicked);
    }
}
Copy after login

If you are interested to learn more about dialogue windows, the following video describes how to implement a JDialog JOptionPane message.

To summarize, Java’s Swing toolkit offers a set of components that enable developers to create user-friendly, visually structured GUIs. The library uses top-level containers like JFrame, JDialog, and JApplet, alongside essential elements like JPanel and JOptionPane.


References:

Oracle Docs. (n.d.a). Swing. Oracle. https://docs.oracle.com/javase/8/docs/technotes/guides/swing/

Oracle Docs. (n.d.b). Using Top-Level Containers. The Java™ Tutorials. Oracle. https://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html

Oracle Docs. (n.d.c). Java Applets. The Java™ Tutorials. Oracle. https://docs.oracle.com/javase/tutorial/deployment/applet/index.html


Originally published by Alex.omegapy at Medium on November 3, 2024.

The above is the detailed content of Creating Java GUIs with Swing Components. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

See all articles