Page Content

Tutorials

What is a JTextArea in Java? & What is a JCheckBox in Java?

JTextArea in Java

Developers can create graphical user interfaces (GUIs) by using Swing, a robust Java toolkit that offers a wide range of classes and interfaces to support visual components. Swing components are primarily “lightweight,” which means they are built entirely in Java and do not rely on platform-specific “peers,” in contrast to the more traditional Abstract Windowing Toolkit (AWT). This enables them to retain a similar appearance and feel across various operating systems.

Multiline text entry and display are intended uses for Swing’s JTextArea class. Large text blocks can be seen or entered using it as a little editing window. The JTextComponent class, the superclass of all text components, is extended by JTextArea.

Constructors: JTextArea(int numRows, int numColumns): Indicates the text area’s width (in characters) and height (in lines). It is possible to specify the initial text using JTextArea(String str, int numLines, int numChars):.

Key Methods:

  1. append(String str): Appends the specified string to the end of the current text.
  2. insert(String str, int index): Inserts a string at a specified index.
  3. replaceRange(String str, int startIndex, int endIndex): Replaces a range of characters with a new string.
  4. getText(): Retrieves the current text.
  5. setText(String str): Sets the text content.

The inability of JTextArea to automatically scroll when the text goes beyond its apparent bounds is a frequent problem. Usually, a JScrollPane encloses JTextArea to provide scrolling capability.

Code Example for JTextArea:

import java.awt.*;
import javax.swing.*;
public class JTextAreaStuff extends JFrame {
    JTextArea myTextArea = new JTextArea(10, 40); // 10 rows, 40 columns
    JTextAreaStuff() {
        setupGUI();
    }
    private void setupGUI() {
        Container c = getContentPane();
        // Add the JTextArea directly, without a JScrollPane for simplicity in this brief example
        // For actual applications, wrapping in JScrollPane is recommended
        c.add(myTextArea);
        setSize(200, 200);
        setVisible(true);
        setTitle("JTextArea Demo");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Make sure the program exits when the window is closed
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new JTextAreaStuff());
    }
}

Code Output for JTextArea (Conceptual): A window titled “JTextArea Demo” will appear, containing a JTextArea that is approximately 10 lines high and 40 characters wide, where text can be typed.

JList

A graphical component offered by the JList class shows a list of things from which a user can choose one or more. It can show lists of practically any object, though strings are frequently used to populate it.

Constructors JList(Object[] listData): Produces a JList that shows the contents of the array that is supplied. Using items from a Vector, JList(Vector listData) generates a JList.

Event Handling: JList handles events by creating a ListSelectionEvent whenever a user adds, modifies, or removes an item. The valueChanged(ListSelectionEvent le) method is defined by the ListSelectionListener interface, which you implement to handle these events. The index of the first item picked can be obtained using getSelectedIndex(), and an array of indices for multiple selections can be obtained using getSelectedIndices(). You can use setSelectionMode() to set the selection mode (single or multiple).

JList frequently benefits from being encapsulated in a JScrollPane to enable automated scrolling for lengthy lists, much as JTextArea.

Code Example for JList:

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
class ListDemo implements ListSelectionListener {
    JList<String> jlst;
    JLabel jlab;
    JScrollPane jscrlp;
    String names[] = { "Sherry", "Jon", "Rachel", "Sasha", "Josselyn", "Randy",
                       "Tom", "Mary", "Ken", "Andrew", "Matt", "Todd" };
    ListDemo() {
        JFrame jfrm = new JFrame("JList Demo");
        jfrm.setLayout(new FlowLayout());
        jfrm.setSize(200, 160);
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jlst = new JList<String>(names);
        jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Single selection mode
        jscrlp = new JScrollPane(jlst);
        jscrlp.setPreferredSize(new Dimension(120, 90));
        jlab = new JLabel("Please choose a name");
        jlst.addListSelectionListener(this); // Register the listener
        jfrm.add(jscrlp);
        jfrm.add(jlab);
        jfrm.setVisible(true);
    }
    public void valueChanged(ListSelectionEvent le) {
        // Ensure the event is not still adjusting (fired multiple times during a single change)
        if (!le.getValueIsAdjusting()) {
            int idx = jlst.getSelectedIndex();
            if (idx != -1) {
                jlab.setText("Current selection: " + names[idx]);
            } else {
                jlab.setText("Please choose a name");
            }
        }
    }
    public static void main(String args[]) {
        SwingUtilities.invokeLater(() -> new ListDemo());
    }
}

Code Output for JList (Conceptual): A window titled “JList Demo” will appear, displaying a scrollable list of names. Below the list, a label will initially say “Please choose a name.” When a name is clicked, the label will update to “Current selection: [Selected Name]”.

JCheckBox

Swing’s JCheckBox class functions as a check box that lets users choose or deselect options. Because it is descended from AbstractButton and JToggleButton, it is a unique kind of button.

Constructors:

  • JCheckBox(String str): Creates a check box with the specified text label.
  • JCheckBox(String s, boolean state): Sets the initial selected state of the check box.
  • JCheckBox(Icon i): Creates a checkbox with an icon.

Event Handling: A JCheckBox generates an ItemEvent upon selection or deselection. The ItemListener interface, which defines the itemStateChanged(ItemEvent ie) method, is implemented to deal with this. Within this method, you may use isSelected() to find the current state of the event after casting ie.getItem() to JCheckBox to obtain a reference to the component that generated it.

Code Example for JCheckBox:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CBDemo implements ItemListener {
    JLabel jlabSelected;
    JLabel jlabChanged;
    JCheckBox jcbAlpha;
    JCheckBox jcbBeta;
    JCheckBox jcbGamma;
    CBDemo() {
        JFrame jfrm = new JFrame("Demonstrate Check Boxes");
        jfrm.setLayout(new FlowLayout());
        jfrm.setSize(280, 150);
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jlabSelected = new JLabel("");
        jlabChanged = new JLabel("");
        jcbAlpha = new JCheckBox("Alpha");
        jcbBeta = new JCheckBox("Beta");
        jcbGamma = new JCheckBox("Gamma");
        jcbAlpha.addItemListener(this);
        jcbBeta.addItemListener(this);
        jcbGamma.addItemListener(this);
        jfrm.add(jcbAlpha);
        jfrm.add(jcbBeta);
        jfrm.add(jcbGamma);
        jfrm.add(jlabChanged);
        jfrm.add(jlabSelected);
        jfrm.setVisible(true);
    }
    public void itemStateChanged(ItemEvent ie) {
        JCheckBox cb = (JCheckBox) ie.getItem(); // Get reference to the changed checkbox
        if (cb.isSelected()) {
            jlabChanged.setText(cb.getText() + " was just selected.");
        } else {
            jlabChanged.setText(cb.getText() + " was just cleared.");
        }
        String str = "";
        if (jcbAlpha.isSelected()) str += "Alpha ";
        if (jcbBeta.isSelected()) str += "Beta ";
        if (jcbGamma.isSelected()) str += "Gamma";
        jlabSelected.setText("Selected check boxes: " + str);
    }
    public static void main(String args[]) {
        SwingUtilities.invokeLater(() -> new CBDemo());
    }
}

Code Output for JCheckBox (Conceptual): A window titled “Demonstrate Check Boxes” will show three check boxes labeled “Alpha,” “Beta,” and “Gamma.” Below them, two labels will display the last action (e.g., “Alpha was just selected.”) and a list of all currently selected check boxes (e.g., “Selected check boxes: Alpha Beta”).

Model-View-Controller (MVC) Programming Paradigm

The Model, View, and Controller are the three different components that make up an application according to the Model-View-Controller (MVC) programming model. In addition to managing complexity, this division attempts to increase the modularity and extensibility of applications.

  1. Model: Holds the information that characterises the part. A field showing whether the box is checked or unchecked, for instance, would be included in the model for a JCheckBox.
  2. View: Shows the component on the screen with the model’s data reflected. The component’s appearance is determined by it.
  3. Controller: User interaction with the component is managed by the controller. In response to user interaction (such as clicking), the controller modifies the model, which causes the view to change.

The model-delegate architecture, also known as the separable model architecture, is a modified form of the traditional MVC design that Swing utilises. This adaption combines the View and Controller into a UI delegate, which is a single logical entity. A “pluggable look and feel,” which enables the rendering of a component to be altered without compromising its underlying logic or data, is made possible by this method. The essential idea behind Swing’s architecture is still the separation of concerns, even with this change.

Consider it analogous to a remote-controlled toy car:

  • Model: The automotive vehicle’s internal condition, including its speed, battery level, and forward or backward motion.
  • View: You can see the actual toy car, with wheels turning and lights on and off to represent its current condition.
  • Controller: The handheld control device. The remote control changes the car’s internal state (Model) when you push a button (user interaction), which makes the vehicle move (View).

Without having to replace the car’s fundamental mechanics, this division makes it simpler to alter the vehicle’s appearance or control system.

Index