Firing Item Events and implement ItemSelectable - Java Swing

Java examples for Swing:Item Event

Description

Firing Item Events and implement ItemSelectable

Demo Code

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

import javax.swing.event.EventListenerList;

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

  public Object[] getSelectedObjects() {
    return null;// www  .j  a  v  a  2  s  .c o  m
  }

  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);

    // Get list of listeners
    Object[] listeners = listenerList.getListenerList();

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

Related Tutorials