Open In App

Java Swing | JToggleButton Class

Improve
Improve
Like Article
Like
Save
Share
Report

A JToggleButton is a two-state button. The two states are selected and unselected. The JRadioButton and JCheckBox classes are subclasses of this class. When the user presses the toggle button, it toggles between being pressed or unpressed. JToggleButton is used to select a choice from a list of possible choices. 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.

Constructors in JToggleButton: 

  1. JToggleButton(): Creates an initially unselected toggle button without setting the text or image.
  2. JToggleButton(Action a): Creates a toggle button where properties are taken from the Action supplied.
  3. JToggleButton(Icon icon): Creates an initially unselected toggle button with the specified image but no text.
  4. JToggleButton(Icon icon, boolean selected): Creates a toggle button with the specified image and selection state, but no text.
  5. JToggleButton(String text): Creates an unselected toggle button with the specified text.
  6. JToggleButton(String text, boolean selected): Creates a toggle button with the specified text and selection state.
  7. JToggleButton(String text, Icon icon): Creates a toggle button that has the specified text and image, and that is initially unselected.
  8. JToggleButton(String text, Icon icon, boolean selected): Creates a toggle button with the specified text, image, and selection state.

Commonly Used Methods: 

Method Description
getAccessibleContext() Gets the AccessibleContext associated with this JToggleButton.
getUIClassID() Returns a string that specifies the name of the l&f class that renders this component.
paramString() Returns a string representation of this JToggleButton.
updateUI() Resets the UI property to a value from the current look and feel.

Below programs illustrates the JToggleButton class: 

1. Java program to implement JToggleButton Events with the ItemListener: In this program, we are creating the frame using JFrame(). Here, setDefaultCloseOperation() is used to set close option for frame. Using JToggleButton() a button is created. Instantiate the ItemListener which contain only itemStateChanged() method that automatically invoked when button is clicked. Event is generated on the button and accordingly, output is printed to the Console. Attach all the Listeners and adding ItemListener to the button. Add button to the frame and setting the size of the frame.

Java




import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
 
public class JToggleButtonExamp {
 
    // Main Method
    public static void main(String args[])
    {
 
        // create a frame and set title
        JFrame frame = new JFrame("Selecting Toggle");
 
        // set the default close operation of the frame
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        // create a ToggleButton
        JToggleButton toggleButton = new JToggleButton("Toggle Button");
 
        // ItemListener is notified whenever you click on the Button
        ItemListener itemListener = new ItemListener() {
 
            // itemStateChanged() method is invoked automatically
            // whenever you click or unclick on the Button.
            public void itemStateChanged(ItemEvent itemEvent)
            {
 
                // event is generated in button
                int state = itemEvent.getStateChange();
 
                // if selected print selected in console
                if (state == ItemEvent.SELECTED) {
                    System.out.println("Selected");
                }
                else {
 
                    // else print deselected in console
                    System.out.println("Deselected");
                }
            }
        };
 
        // Attach Listeners
        toggleButton.addItemListener(itemListener);
        frame.add(toggleButton, BorderLayout.NORTH);
        frame.setSize(300, 125);
        frame.setVisible(true);
    }
}


Output:

2. Java program to implement JToggleButton Event using ActionListener: Here, a JToggleButton is created on the JFrame. Then, we define the ActionListener. actionPerformed() is the only method in ActionListener() which is invoked whenever a registered component is clicked. abstractButton.getModel().isSelected() returns true if button is selected else return false. Attach the Listener to the ToggleButton.

Java




import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractButton;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
 
public class JToggleButtonExamp {
 
    // Main Method
    public static void main(String args[])
    {
 
        // create the JFrame
        JFrame frame = new JFrame("Selecting Toggle");
 
        // set default close operation for frame
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        // create a ToggleButton
        JToggleButton toggleButton = new JToggleButton("Toggle Button");
 
        // Define ActionListener
 
        ActionListener actionListener = new ActionListener()
        {
 
            // actionPerformed() method is invoked
            // automatically whenever you click on
            // registered component
            public void actionPerformed(ActionEvent actionEvent)
            {
     
                AbstractButton abstractButton =
                (AbstractButton)actionEvent.getSource();
     
                // return true or false according
                // to the selection or deselection
                // of the button
                boolean selected = abstractButton.getModel().isSelected();
     
                System.out.println("Action - selected=" + selected + "\n");
            }
          };
        // Attach Listeners
        toggleButton.addActionListener(actionListener);
 
        // add ToggleButton to the frame
        frame.add(toggleButton, BorderLayout.NORTH);
 
        // set size of the frame
        frame.setSize(300, 125);
 
        frame.setVisible(true);
    }
}


Output :

Note: The above programs might not run in an online IDE. Please use an offline compiler.

Reference: https://docs.oracle.com/javase/7/docs/api/javax/swing/JToggleButton.html
 



Last Updated : 05 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads