Java - Example: Creating a Simple GUI with Event Handling

Example for Creating a Simple GUI with Event Handling in Java

Let's build a basic GUI application that uses JButton, JLabel, JTextField, and event handling.

import javax.swing.*; // Importing Swing components
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

// Define the main class
public class SimpleGUIWithEvents {
    // Entry point of the application
    public static void main(String[] args) {
        // Create a new JFrame (window)
        JFrame frame = new JFrame("Simple GUI with Event Handling");

        // Set the default close operation so the application exits when the window is closed
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Create a new JLabel (text label)
        JLabel label = new JLabel("Enter your name:");

        // Create a new JTextField (text field)
        JTextField textField = new JTextField(20); // 20 columns wide

        // Create a new JButton (button)
        JButton button = new JButton("Submit");

        // Create a new JLabel to display the message
        JLabel messageLabel = new JLabel();

        // Add an ActionListener to the button to handle click events
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Get the text from the text field
                String name = textField.getText();
                // Set the text of the message label
                messageLabel.setText("Hello, " + name + "!");
            }
        });

        // Create a JPanel to hold the components
        JPanel panel = new JPanel();
        
        // Add the label, text field, button, and message label to the panel
        panel.add(label);
        panel.add(textField);
        panel.add(button);
        panel.add(messageLabel);

        // Add the panel to the frame
        frame.add(panel);

        // Set the size of the window
        frame.setSize(400, 200);
        
        // Make the window visible
        frame.setVisible(true);
    }
}

Import Statements:

javax.swing.*: Imports the whole Swing framework.

java.awt.event.Java.awt.event and ActionEvent.ActionListener: Classes that handle action events are imported.

Main Class Definition:

The main function of the SimpleGUIWithEvents class serves as the application's entry point.

Creating the JFrame:

JFrame frame = new JFrame("Simple GUI with Event Handling");: Opens a new window labeled "Simple GUI with Event Handling."

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): This ensures that the program terminates when the window is closed.

Creating the JLabel:

JLabel label = new JLabel("Enter your name:");: Produces a label with the text "Enter your name:".

Creating the JTextField:

JTextField textField = new JTextField(20);: This constructs a text field with 20 columns.

Creating the JButton:

JButton button = new JButton("Submit");: Constructs a button with the label "Submit".

Creating the Message JLabel:

JLabel messageLabel = new JLabel();: This creates an empty label to show the message on.

Adding an ActionListener to the Button:

button.addActionListener(new ActionListener() {... });: Adds a button event listener.

"public void" actionPerformed(ActionEvent e) {... }: Specifies what occurs when the button is clicked. It extracts the content from the text field and changes the text of the message label to "Hello, [name]!"

Creating and Adding Components to JPanel:

JPanel panel is the new JPanel();: Builds a panel to contain the components.

panel.add(label); panel.add(textField); panel.add(button); panel.add(messageLabel);: The label, text field, button, and message label are all added to the panel.

Adding JPanel to JFrame:

frame.add(panel);: Attaches the panel to the frame.

Setting JFrame Properties:

frame.setSize(400, 200): Determines the window's size.

frame.setVisible(true): The window is made visible.

logo

Java

Beginner 5 Hours

Example for Creating a Simple GUI with Event Handling in Java

Let's build a basic GUI application that uses JButton, JLabel, JTextField, and event handling.

import javax.swing.*; // Importing Swing components
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

// Define the main class
public class SimpleGUIWithEvents {
    // Entry point of the application
    public static void main(String[] args) {
        // Create a new JFrame (window)
        JFrame frame = new JFrame("Simple GUI with Event Handling");

        // Set the default close operation so the application exits when the window is closed
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Create a new JLabel (text label)
        JLabel label = new JLabel("Enter your name:");

        // Create a new JTextField (text field)
        JTextField textField = new JTextField(20); // 20 columns wide

        // Create a new JButton (button)
        JButton button = new JButton("Submit");

        // Create a new JLabel to display the message
        JLabel messageLabel = new JLabel();

        // Add an ActionListener to the button to handle click events
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Get the text from the text field
                String name = textField.getText();
                // Set the text of the message label
                messageLabel.setText("Hello, " + name + "!");
            }
        });

        // Create a JPanel to hold the components
        JPanel panel = new JPanel();
        
        // Add the label, text field, button, and message label to the panel
        panel.add(label);
        panel.add(textField);
        panel.add(button);
        panel.add(messageLabel);

        // Add the panel to the frame
        frame.add(panel);

        // Set the size of the window
        frame.setSize(400, 200);
        
        // Make the window visible
        frame.setVisible(true);
    }
}

Import Statements:

javax.swing.*: Imports the whole Swing framework.

java.awt.event.Java.awt.event and ActionEvent.ActionListener: Classes that handle action events are imported.

Main Class Definition:

The main function of the SimpleGUIWithEvents class serves as the application's entry point.

Creating the JFrame:

JFrame frame = new JFrame("Simple GUI with Event Handling");: Opens a new window labeled "Simple GUI with Event Handling."

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): This ensures that the program terminates when the window is closed.

Creating the JLabel:

JLabel label = new JLabel("Enter your name:");: Produces a label with the text "Enter your name:".

Creating the JTextField:

JTextField textField = new JTextField(20);: This constructs a text field with 20 columns.

Creating the JButton:

JButton button = new JButton("Submit");: Constructs a button with the label "Submit".

Creating the Message JLabel:

JLabel messageLabel = new JLabel();: This creates an empty label to show the message on.

Adding an ActionListener to the Button:

button.addActionListener(new ActionListener() {... });: Adds a button event listener.

"public void" actionPerformed(ActionEvent e) {... }: Specifies what occurs when the button is clicked. It extracts the content from the text field and changes the text of the message label to "Hello, [name]!"

Creating and Adding Components to JPanel:

JPanel panel is the new JPanel();: Builds a panel to contain the components.

panel.add(label); panel.add(textField); panel.add(button); panel.add(messageLabel);: The label, text field, button, and message label are all added to the panel.

Adding JPanel to JFrame:

frame.add(panel);: Attaches the panel to the frame.

Setting JFrame Properties:

frame.setSize(400, 200): Determines the window's size.

frame.setVisible(true): The window is made visible.

Related Tutorials

Frequently Asked Questions for Java

Java is known for its key features such as object-oriented programming, platform independence, robust exception handling, multithreading capabilities, and automatic garbage collection.

The Java Development Kit (JDK) is a software development kit used to develop Java applications. The Java Runtime Environment (JRE) provides libraries and other resources to run Java applications, while the Java Virtual Machine (JVM) executes Java bytecode.

Java is a high-level, object-oriented programming language known for its platform independence. This means that Java programs can run on any device that has a Java Virtual Machine (JVM) installed, making it versatile across different operating systems.

Deadlock is a situation in multithreading where two or more threads are blocked forever, waiting for each other to release resources.

Functional programming in Java involves writing code using functions, immutability, and higher-order functions, often utilizing features introduced in Java 8.

A process is an independent program in execution, while a thread is a lightweight subprocess that shares resources with other threads within the same process.

The Comparable interface defines a natural ordering for objects, while the Comparator interface defines an external ordering.

The List interface allows duplicate elements and maintains the order of insertion, while the Set interface does not allow duplicates and does not guarantee any specific order.

String is immutable, meaning its value cannot be changed after creation. StringBuffer and StringBuilder are mutable, allowing modifications to their contents. The main difference between them is that StringBuffer is synchronized, making it thread-safe, while StringBuilder is not.

Checked exceptions are exceptions that must be either caught or declared in the method signature, while unchecked exceptions do not require explicit handling.

ArrayList is backed by a dynamic array, providing fast random access but slower insertions and deletions. LinkedList is backed by a doubly-linked list, offering faster insertions and deletions but slower random access.

Autoboxing is the automatic conversion between primitive types and their corresponding wrapper classes. For example, converting an int to Integer.

The 'synchronized' keyword in Java is used to control access to a method or block of code by multiple threads, ensuring that only one thread can execute it at a time.

Multithreading in Java allows concurrent execution of two or more threads, enabling efficient CPU utilization and improved application performance.

A HashMap is a collection class that implements the Map interface, storing key-value pairs. It allows null values and keys and provides constant-time performance for basic operations.

Java achieves platform independence by compiling source code into bytecode, which is executed by the JVM. This allows Java programs to run on any platform that has a compatible JVM.

The Serializable interface provides a default mechanism for serialization, while the Externalizable interface allows for custom serialization behavior.

The 'volatile' keyword in Java indicates that a variable's value will be modified by multiple threads, ensuring that the most up-to-date value is always visible.

Serialization is the process of converting an object into a byte stream, enabling it to be saved to a file or transmitted over a network.

The finalize() method is called by the garbage collector before an object is destroyed, allowing for cleanup operations.

The 'final' keyword in Java is used to define constants, prevent method overriding, and prevent inheritance of classes, ensuring that certain elements remain unchanged.

Garbage collection is the process by which the JVM automatically deletes objects that are no longer reachable, freeing up memory resources.

'throw' is used to explicitly throw an exception, while 'throws' is used in method declarations to specify that a method can throw one or more exceptions.

The 'super' keyword in Java refers to the immediate parent class and is used to access parent class methods, constructors, and variables.

The JVM is responsible for loading, verifying, and executing Java bytecode. It provides an abstraction between the compiled Java program and the underlying hardware, enabling platform independence.

line

Copyrights © 2024 letsupdateskills All rights reserved