Java AWT ItemSelectable implement to fire item event

Description

Java AWT ItemSelectable implement to fire item event

import java.awt.BorderLayout;
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.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.EventListenerList;

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

    component.addItemListener(new ItemListener() {
      @Override//from   w ww .ja v  a 2  s  . co m
      public void itemStateChanged(ItemEvent v) {
         System.out.println(v);
      }
    });
    
    f.add(component,BorderLayout.NORTH);
    f.setSize(300, 300);
    f.setVisible(true);

  }
}

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

  public MyComponent() {
     super.addCaretListener(new CaretListener() {
      @Override
      public void caretUpdate(CaretEvent e) {
         fireItemEvent(MyComponent.this.getText(), true); 
      }
     });
  }
  
  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; i++) {
      if (listeners[i] == ItemListener.class) {

        ((ItemListener) listeners[i + 1]).itemStateChanged(evt);
      }
    }
  }
}



PreviousNext

Related