Java Graphical User Interface(GUI): JCheckBox and ItemListener

in #utopian-io6 years ago (edited)

What Will I Learn?

  • The user will learn the concept of JCheckBox.
  • The user will learn how to create a Checkbox.
  • The user will also learn how to change the font of a text.

Requirements

  • A computer System is required for this tutorial.
  • Java Software Development Kit(JDK) must be installed on your computer.
  • An Integrated Development Environment(IDE) such as Eclipse or NetBeans is required to be installed on your computer.

Get JDK here

Get Eclipse here

Get NetBeans here

Difficulty

The codes in this tutorial are around the same level as other tutorials so difficulty level will be same as others - Intermediate.

Tutorial Contents

In the previous tutorials, we have learnt various Swing Components like JFrame, JLabel, JTextField, JPasswordField and JButton. Today, we will look at another interesting Swing Component and the subject of this tutorial:

JCHECKBOX AND ITEMLISTENER

JCHECKBOX

The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".

It is an implementation of a check box -- an item that can be selected or deselected, and which displays its state to the user. By convention, any number of check boxes in a group can be selected.
Buttons can be configured, and to some degree controlled, by actions. Using an Action with a button has many benefits beyond directly configuring a button.

ITEMLISTENER

The Java ItemListener is notified whenever you click on the checkbox. It is notified against ItemEvent. The ItemListener interface is found in java.awt.event package. It has only one method: itemStateChanged().
The class which processes the ItemEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addItemListener() method. When the action event occurs,
that object's itemStateChanged method is invoked.

itemStateChanged()

The itemStateChanged() method is invoked automatically whenever you click or unclick on the registered checkbox component.

In this tutorial, we will create two JCheckBox Objects; “Bold Font” and “Italic Font”, we will also create a JTextField object from previous tutorials.

The JTextField object will contain a line of text and we will use the checkbox objects to change the font of the text to either Bold or Italic or Both when selected.

1.png

2.png

3.png

CODE BLOCK

CHECKBOX CLASS
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class checkBox extends JFrame {
    private JTextField field;
    private JCheckBox firstBox;
    private JCheckBox secondBox;
    public checkBox() {
        super("JCheckBox Demo");
        setLayout(new FlowLayout());
        field = new JTextField("Hello Utopian, JCheckBox Demo", 19);
        field.setFont(new Font("Calibri", Font.PLAIN, 18));
        add(field);
        firstBox = new JCheckBox("Bold Font");
        add(firstBox);
        secondBox = new JCheckBox("Italic Font");
        add(secondBox);
        newClass eventHandler = new newClass();
        firstBox.addItemListener(eventHandler);
        secondBox.addItemListener(eventHandler);
    }
    private class newClass implements ItemListener {
        public void itemStateChanged(ItemEvent event) {
            Font f = null;
            if (firstBox.isSelected() && secondBox.isSelected())
                f = new Font("Serif", Font.BOLD + Font.ITALIC, 18);
            else if (firstBox.isSelected())
                f = new Font("Serif", Font.BOLD, 18);
            else if (secondBox.isSelected())
                f = new Font("Serif", Font.ITALIC, 18);
            else
                f = new Font("Serif", Font.PLAIN, 18);
            field.setFont(f);
        }
    }
}
MAIN CLASS
import javax.swing.JFrame;
public class Main {
    public static void main (String args []) {
        checkBox Object = new checkBox();
        Object.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Object.setSize(350,150);
        Object.setVisible(true);
    }
}

CHECKBOX CLASS

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

These are Import Statements. Import Statements are used to reference methods that are in other packages. Java comes with a bunch of in built methods and these methods are in different packages. When the user imports a class, the user has access to all methods in the class because they are automatically imported.

public class checkBox extends JFrame {

This is the name of the current class. When you start a new class, it must be saved with a name. This class extends JFrame. In Java, it is possible for classes to inherit properties of another class. Here, this class inherits basic Frame properties like a window with close, maximize and minimize buttons from the JFrame class. The extends keyword is used to achieve this.

private JTextField field;

This is a variable of JTextField type. This object will allow the user to enter a single, editable line of text.

The line of text entered by the user will then be stored in the object field.

private JCheckBox firstBox;

This object of JCheckBox type will create a selectable checkbox on the screen.

It will be associated with an event. When the user selects it, an event will occur.

private JCheckBox secondBox;

A second JCheckBox type variable to create a checkbox for the user to select.

Upon user selection, an event occurs.

public checkBox() {

A Constructor is a block of code that lets you initialize variables immediately an object is created. Methods can be created and called later but with constructors, initialization is done immediately. Constructors have the same name as the class name and is called when an object of the class in created.
The above constructor does not carry any arguments and is created to hold the JCheckBox components.

super("JCheckBox Demo");

The super keyword is used here to refer to properties of a superclass; in this case the JFrame class.
In this context, it is used to set the title of the newly created window. The title of the window is “JCheckBox Demo”

setLayout(new FlowLayout());

The FlowLayout class. This provides a simple layout that is used by JFrame components.

field = new JTextField("Hello Utopian, JCheckBox Demo", 19);

Here, the user is allowed to enter a single line of text. The user can edit the text if the user wishes. The newly entered text is then assigned to the object field. The maximum number of characters allowed for this text is 19.

field.setFont(new Font("Calibri", Font.PLAIN, 18));

The .setFont is an inbuilt method in Java used to set the font of a text. Here, the programmer chooses the font of choice; “Calibri” sets the font to Plain and the font size to 18.

add[field]

This will add the field object to the window.

firstBox = new JCheckBox("Bold Font");

This line of code will create a selectable checkbox. A String “Bold Font” will be displayed next to the check box. This will allow the user to know the function of the checkbox.

add(firstBox);

This adds the created checkbox to the JFrame container

secondBox = new JCheckBox("Italic Font");

A second checkbox is created with the string “Italic Font” allowing the user to know the function of the checkbox.

add(secondBox);

The checkbox is added to the screen.

newClass eventHandler = new newClass();
firstBox.addItemListener(eventHandler);
secondBox.addItemListener(eventHandler);

When the new class which implements the ItemListener interface is created, an object of the new class is also created. The

.addItemListerer[]

method is then used to pass execution instructions to the JCheckBox component.

ITEMLISTENER CLASS

private class newClass implements ItemListener {

ItemListener is an interface (not a class) that contains a single method.

A class that implements the interface must contain an itemStateChanged() method. The ItemEvent parameter is an Event object that represents an event.

public void itemStateChanged(ItemEvent event) {

This is the single method for the listener interface for receiving action events. The ItemEvent is a class and event is an instance of that class. event can be used to call it’s properties.

Font f = null;

A variable of type Font set to null. The variable “f” will hold the font value assigned to it.

if (firstBox.isSelected() && secondBox.isSelected())

The java built in .isSelected() method is used in association with checkboxes.
This means if the indicated checkbox is clicked (selected).
The if statement has two conditions; if the first and second box is selected.

f = new Font("Serif", Font.BOLD + Font.ITALIC, 18);

This statement will be executed if the condition in the if statement is true. This statement sets a new font “BOLD” and “ITALIC” with size 18 and assigns it to the value f.

else if (firstBox.isSelected())

From previous tutorials, we can tell that this is a nested if statement. A second condition if the first condition is not true.

f = new Font("Serif", Font.BOLD, 18);

This statement will be executed if the condition in the else if statement is true. This statement sets a new font “BOLD” with size 18 and assigns it to the value f.

else if (secondBox.isSelected())

Another nested if statement with a condition. Condition here is “if secondBox Is selected”.

f = new Font("Serif", Font.ITALIC, 18);

This changes the font to ITALIC if the condition above is true.

else
f = new Font("Serif", Font.PLAIN, 18);

If none of the conditions are met, the font remains in its default PLAIN setting.

field.setFont(f); 

Now that the Fonts have been set and assigned to the variable f, the variable is passed as an argument to the .setFont() method. When any of the checkboxes is clicked, the font changes to the required font.

MAIN CLASS

import javax.swing.JFrame;

This is an import statement. This statement is used specifically to import the JFrame class from Application Program Interface (API). This allows the user to use all methods contained in it.

public class Main {

This is just like creating a new file or document and saving it with a name. This is the name of the new class created.

public static void main (String args []) {

The Java main method. Every program must contain this method in order to execute. It is the point from which the program begins execution.
A program without this method will not execute.

checkbox Object = new checkBox();

An Object of the checkBox class is created. This enables the user to call in built GUI methods that will help to properly display the JCheckBox component to the screen.

Object.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

This inbuilt method needs to be called before the program is run . This method states the default behavior of the windows when the “close”(x) button is clicked.
Here, it tells the window to close.

Object.setSize(350,150);

This is to set the size of the object to the specified width and height. In this case, the specified dimensions are (350,150).

Values of width and height are non-negative integers. The constructors that allow you to create a dimension do not prevent you from setting a negative value for these properties. If the value of width or height is negative, the behavior of some methods defined by other objects is undefined.

Object.setVisible(true);

This simply determines whether a component is displayed on the screen. It has two states. True and false.

With setVisible( false ), if the Component is not already marked invisible, setVisible calls invalidate() which invalidates the Container’s layout and the chain of parents since there is now more screen real estate in the Container and the positions of the siblings must be adjusted to flow into the freed space.

With setVisible( true ), if the Component is not already marked visible,setVisible calls invalidate() which invalidates the Container’s layout and the chain of parents since there is now less screen real estate in the Container and the positions of the siblings must be adjusted to squeeze in this new Component.

4.png

When the program is run and both Bold Font and Italic Font checkboxes are selected, The font of the JTextField text becomes Bold and Italicized.

5.png

If just the Bold Font alone is selected, the text becomes plain and Bold.

6.png

If the Italics Font alone is selected, the text is italicized.

7.png

If none of the checkboxes is selected, the text remains plain.

8.png

9.png

10.png

Source Codes from GitHub Account.

You can get the codes here if you want to try it on your own.

REFERENCES

Curriculum

Similar posts already posted on Utopian are:



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Your contribution cannot be approved because it is a duplicate. It is very similar to a contribution that was already accepted here.

You can contact us on Discord.
[utopian-moderator]

Okay thanks. I was unaware that there already was something similar.

Coin Marketplace

STEEM 0.30
TRX 0.12
JST 0.033
BTC 64303.16
ETH 3137.29
USDT 1.00
SBD 3.97