Toggle button with ItemListener : ItemListener « Swing Event « Java Tutorial






Toggle button with ItemListener
import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;

public class ToggleButtonCheckBoxRadioButton extends JFrame {
  public static void main(String[] args) {
    ToggleButtonCheckBoxRadioButton that = new ToggleButtonCheckBoxRadioButton();
    that.setVisible(true);
  }

  public ToggleButtonCheckBoxRadioButton() {
    setSize(450, 350);

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    getContentPane().add(new TogglePanel(), BorderLayout.SOUTH);
  }
}

class TogglePanel extends JPanel {
  public TogglePanel() {
    JToggleButton tog = new JToggleButton("Toggle");
    ItemListener listener = new ItemListener() {
      public void itemStateChanged(ItemEvent e) {
        AbstractButton src = (AbstractButton) (e.getSource());
        System.out.println("Toggle: " + src.getText());
      }
    };
    tog.addItemListener(listener);
    add(tog);

    JCheckBox cbox = new JCheckBox("Checkbox");
    cbox.addItemListener(listener);
    add(cbox);
    ButtonGroup btngroup = new ButtonGroup();
    for (int i = 1; i <= 3; i++) {
      JRadioButton radio = new JRadioButton("Radio " + i);
      btngroup.add(radio);
      radio.addItemListener(listener);
      add(radio);
    }
  }
}








15.20.ItemListener
15.20.1.How to Write an Item ListenerHow to Write an Item Listener
15.20.2.Toggle button with ItemListenerToggle button with ItemListener
15.20.3.ComboBox with ItemListenerComboBox with ItemListener
15.20.4.Firing Item Events
15.20.5.ItemListener for JRadioButton