Java by API/java.awt/ItemSelectable

Материал из Java эксперт
Перейти к: навигация, поиск

implements ItemSelectable

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





ItemSelectable: getSelectedObjects()

 
import java.awt.BorderLayout;
import java.awt.ItemSelectable;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class MainClass {
  public static void main(final String args[]) {
    final String labels[] = { "A", "B", "C", "D", "E" };
    JFrame frame = new JFrame("Selecting JComboBox");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JComboBox comboBox = new JComboBox(labels);
    frame.add(comboBox, BorderLayout.SOUTH);
    ItemListener itemListener = new ItemListener() {
      public void itemStateChanged(ItemEvent itemEvent) {
        int state = itemEvent.getStateChange();
        String stateString = 
          ((state == ItemEvent.SELECTED) ? "Selected" : "Deselected");
        System.out.println("Item: " + itemEvent.getItem());
        System.out.println(", State: " + stateString);
        ItemSelectable is = itemEvent.getItemSelectable();
        System.out.println(", Selected: " + selectedString(is));
      }
    };
    comboBox.addItemListener(itemListener);
    frame.setSize(400, 200);
    frame.setVisible(true);
  }
  static private String selectedString(ItemSelectable is) {
    Object selected[] = is.getSelectedObjects();
    return ((selected.length == 0) ? "null" : (String)selected[0]);
  }  
}