Firing Item Events : ItemListener « Swing Event « Java Tutorial






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

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.EventListenerList;

public class Main {
  public static void main(String[] argv) throws Exception {
    MyComponent component = new MyComponent();
    JFrame f = new JFrame();

    f.add(component);
    f.setSize(300, 300);
    f.setVisible(true);

  }
}

class MyComponent extends JTextField implements ItemSelectable {
  protected EventListenerList listenerList = new EventListenerList();

  public Object[] getSelectedObjects() {
    return new String[] { "a", "b", "c" };
  }

  public void addItemListener(ItemListener l) {
    listenerList.add(ItemListener.class, l);
  }

  public void removeItemListener(ItemListener l) {
    listenerList.remove(ItemListener.class, l);
  }
  void fireItemEvent(Object item, boolean sel) {
    ItemEvent evt = new ItemEvent(this, ItemEvent.ITEM_STATE_CHANGED, item,
        sel ? ItemEvent.SELECTED : ItemEvent.DESELECTED);

    Object[] listeners = listenerList.getListenerList();

    for (int i = 0; i < listeners.length - 2; i += 2) {
      if (listeners[i] == ItemListener.class) {
        ((ItemListener) listeners[i + 1]).itemStateChanged(evt);
      }
    }
  }
}








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