JToggleButton is a button that has two states. Pressed and not pressed. : JToggleButton « Swing « Java Tutorial






import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JToggleButton;

public class ToggleButton extends JDialog implements ActionListener {

  private JToggleButton red = new JToggleButton("red");

  private JToggleButton green = new JToggleButton("green");

  private JToggleButton blue = new JToggleButton("blue");

  private JPanel display = new JPanel();

  public ToggleButton() {
    JPanel bottom = new JPanel();
    JPanel leftPanel = new JPanel();

    red.addActionListener(this);
    green.addActionListener(this);
    blue.addActionListener(this);

    leftPanel.add(red);
    leftPanel.add(green);
    leftPanel.add(blue);
    bottom.add(leftPanel);

    display.setBackground(Color.black);

    bottom.add(display);
    add(bottom);

    pack();
    setResizable(false);
    setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    setVisible(true);
  }

  public static void main(String[] args) {
    new ToggleButton();
  }

  public void actionPerformed(ActionEvent e) {
    Color color = display.getBackground();
    int red = color.getRed();
    int green = color.getGreen();
    int blue = color.getBlue();

    if (e.getActionCommand() == "red") {
      if (red == 0) {
        red = 255;
      } else {
        red = 0;
      }
    }

    if (e.getActionCommand() == "green") {
      if (green == 0) {
        green = 255;
      } else {
        green = 0;
      }
    }

    if (e.getActionCommand() == "blue") {
      if (blue == 0) {
        blue = 255;
      } else {
        blue = 0;
      }
    }

    Color setCol = new Color(red, green, blue);
    display.setBackground(setCol);
  }
}








14.8.JToggleButton
14.8.1.Creating JToggleButton Components
14.8.2.JToggleButton is a button that has two states. Pressed and not pressed.
14.8.3.Listening to JToggleButton Events with an ActionListenerListening to JToggleButton Events with an ActionListener
14.8.4.Listening to JToggleButton Events with an ItemListenerListening to JToggleButton Events with an ItemListener
14.8.5.Listening to JToggleButton Events with a ChangeListenerListening to JToggleButton Events with a ChangeListener
14.8.6.The event sequence for JToggleButton: ActionListener, ItemListener and ChangeListenerThe event sequence for JToggleButton: ActionListener, ItemListener and ChangeListener
14.8.7.Customizing JToggleButton Look and Feel
14.8.8.This class represents the toggle buttons used in toolbars.