Fire Item Events from JTextField in Java

Description

The following code shows how to fire Item Events from JTextField.

Example


import java.awt.ItemSelectable;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
//from w  w w .  j  a va2 s .co  m
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);
      }
    }
  }
}

The code above generates the following result.

Fire Item Events from JTextField in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer