Java AWT ItemListener handle item selection event on JToggleButton

Description

Java AWT ItemListener handle item selection event on JToggleButton

import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

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 Main extends JFrame {
  public Main() {
    setSize(450, 350);//  w w w . j  ava2 s.  c  om

    JPanel togglePanel = new JPanel();
    
    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);
    togglePanel.add(tog);

    JCheckBox cbox = new JCheckBox("Checkbox");
    cbox.addItemListener(listener);
    togglePanel.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);
      togglePanel.add(radio);
    }
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    getContentPane().add(togglePanel, BorderLayout.CENTER);
  }
  
  public static void main(String[] args) {
     Main that = new Main();
     that.setVisible(true);
   }
}



PreviousNext

Related