jtogglebutton

h‮t‬tps://www.theitroad.com

JToggleButton is a Swing component in Java that represents a button which can be toggled on and off. It extends the AbstractButton class and is used to implement buttons that have two states - "selected" and "unselected".

The JToggleButton has the following states:

  • isSelected(): returns true if the toggle button is selected (on), false if it is not selected (off).

It has the following constructors:

  • JToggleButton() - creates a toggle button with no text or icon.
  • JToggleButton(String text) - creates a toggle button with the specified text.
  • JToggleButton(Icon icon) - creates a toggle button with the specified icon.
  • JToggleButton(String text, Icon icon) - creates a toggle button with the specified text and icon.

JToggleButton provides some methods to manipulate the state of the button. For example, you can set whether the button is selected or not using the setSelected(boolean b) method.

Here is an example of how to create and use a JToggleButton:

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;

public class JToggleButtonExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("JToggleButton Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();

        // Create a toggle button
        JToggleButton toggleButton = new JToggleButton("Toggle Button");

        // Add the toggle button to the panel
        panel.add(toggleButton);

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

        // Set the size of the frame
        frame.setSize(300, 200);

        // Display the frame
        frame.setVisible(true);
    }
}

This will create a window containing a toggle button with the text "Toggle Button".