Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Thursday, April 17, 2025

Swing Components, Text Fields, Text Areas. Buttons, Check Boxes; Radio Buttons etc

Swing Components: An Overview

Java Swing provides a comprehensive suite of user interface components that are used to build feature-rich desktop applications. These components are a part of the javax.swing package and are more flexible, platform-independent, and lightweight in comparison to their AWT counterparts. Each Swing component is designed with a high degree of modularity and is capable of supporting advanced event handling, rendering customizations, and accessibility features.

Swing components inherit from the root class javax.swing.JComponent, which provides fundamental properties such as borders, tooltips, double-buffering, and key/mouse event handling. The key advantage of Swing components is their ability to be integrated seamlessly with various layout managers and their adherence to the Model-View-Controller (MVC) architecture.

Below are detailed descriptions of commonly used Swing components:


1. JTextField (Text Field)

A JTextField is a single-line text component used to input or display a line of editable text.

  • Class: javax.swing.JTextField
  • Key Methods:
    • getText() – Retrieves the current text.
    • setText(String text) – Sets the displayed text.
    • setColumns(int) – Sets the width of the text field in terms of character columns.

Example:

JTextField textField = new JTextField(20);

panel.add(textField);


2. JTextArea (Text Area)

The JTextArea component allows the user to enter multiple lines of text. It is often used for larger input fields such as comments, logs, or messages.

  • Class: javax.swing.JTextArea
  • Key Features:
    • Supports line wrapping and scrolling (when used with JScrollPane).
    • Can be editable or read-only.
  • Key Methods:
    • append(String) – Appends text to the area.
    • setLineWrap(boolean) – Enables line wrap.
    • setWrapStyleWord(boolean) – Wraps at word boundaries.

Example:

JTextArea textArea = new JTextArea(5, 20);

textArea.setLineWrap(true);

JScrollPane scrollPane = new JScrollPane(textArea);

panel.add(scrollPane);


3. JButton (Button)

A JButton is a push button that triggers an action when clicked. It can display text, images, or both.

  • Class: javax.swing.JButton
  • Usage: Commonly used to submit data, trigger functions, or navigate interfaces.
  • Event Handling: Listeners such as ActionListener are attached to capture click events.

Example:

JButton button = new JButton("Submit");

button.addActionListener(e -> System.out.println("Button clicked"));

panel.add(button);


4. JCheckBox (Check Box)

The JCheckBox is used to create checkboxes that allow users to select or deselect options independently.

  • Class: javax.swing.JCheckBox
  • Key Methods:
    • isSelected() – Returns true if the box is checked.
    • setSelected(boolean) – Sets the checkbox state.

Example:

JCheckBox checkBox = new JCheckBox("Accept Terms");

panel.add(checkBox);


5. JRadioButton (Radio Button)

The JRadioButton is used to create mutually exclusive options where only one selection is allowed among a group.

  • Class: javax.swing.JRadioButton
  • Grouping: To make a group of radio buttons mutually exclusive, they must be added to a ButtonGroup.

Example:

JRadioButton male = new JRadioButton("Male");

JRadioButton female = new JRadioButton("Female");

ButtonGroup group = new ButtonGroup();

group.add(male);

group.add(female);

panel.add(male);

panel.add(female);


Key Characteristics of Swing Components

Feature

Description

Lightweight

Entirely written in Java, does not rely on native OS components.

Pluggable Look and Feel

Allows customization of GUI appearance without affecting logic.

Platform Independent

Ensures consistent behavior across various operating systems.

MVC Architecture

Promotes separation of data (Model), UI (View), and logic (Controller).

Event-driven

Interactions are captured through event listeners (e.g., ActionListener).

Customizable

Components support rich features like borders, colors, icons, tooltips, etc.



Program:

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;


public class SwingComponentDemo {


    public static void main(String[] args) {

        // Create JFrame

        JFrame frame = new JFrame("Swing Components Demo");

        frame.setSize(500, 400);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setLayout(new FlowLayout());


        // JLabel and JTextField

        JLabel nameLabel = new JLabel("Enter Name:");

        JTextField nameField = new JTextField(20);


        // JLabel and JTextArea

        JLabel addressLabel = new JLabel("Enter Address:");

        JTextArea addressArea = new JTextArea(4, 20);

        addressArea.setLineWrap(true);

        addressArea.setWrapStyleWord(true);

        JScrollPane scrollPane = new JScrollPane(addressArea);


        // JCheckBoxes

        JLabel languageLabel = new JLabel("Select Languages Known:");

        JCheckBox cb1 = new JCheckBox("Java");

        JCheckBox cb2 = new JCheckBox("Python");

        JCheckBox cb3 = new JCheckBox("C++");


        // JRadioButtons (Gender Selection)

        JLabel genderLabel = new JLabel("Select Gender:");

        JRadioButton male = new JRadioButton("Male");

        JRadioButton female = new JRadioButton("Female");

        ButtonGroup genderGroup = new ButtonGroup(); // Grouping the radio buttons

        genderGroup.add(male);

        genderGroup.add(female);


        // JButton

        JButton submitButton = new JButton("Submit");


        // ActionListener for button

        submitButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                String name = nameField.getText();

                String address = addressArea.getText();


                String languages = "";

                if (cb1.isSelected()) languages += "Java ";

                if (cb2.isSelected()) languages += "Python ";

                if (cb3.isSelected()) languages += "C++ ";


                String gender = "";

                if (male.isSelected()) gender = "Male";

                else if (female.isSelected()) gender = "Female";


                // Show collected data

                JOptionPane.showMessageDialog(frame,

                        "Name: " + name + "\n" +

                        "Address: " + address + "\n" +

                        "Languages: " + languages + "\n" +

                        "Gender: " + gender,

                        "Submitted Data",

                        JOptionPane.INFORMATION_MESSAGE);

            }

        });


        // Add components to JFrame

        frame.add(nameLabel);

        frame.add(nameField);


        frame.add(addressLabel);

        frame.add(scrollPane);


        frame.add(languageLabel);

        frame.add(cb1);

        frame.add(cb2);

        frame.add(cb3);


        frame.add(genderLabel);

        frame.add(male);

        frame.add(female);


        frame.add(submitButton);


        // Make the frame visible

        frame.setVisible(true);

    }

}



output:





Conclusion

Swing components form the backbone of desktop GUI applications in Java. They offer a robust and extensible framework that balances ease of use with deep functionality. Whether it is through simple input elements like text fields and buttons, or more structured controls like checkboxes and radio buttons, Swing enables developers to build highly interactive, visually consistent, and platform-independent applications. Understanding these components is foundational for any Java developer involved in building desktop-based software systems.


No comments:

Post a Comment