Java Swing Tutorial - Java ItemEvent.getItemSelectable()








Syntax

ItemEvent.getItemSelectable() has the following syntax.

public ItemSelectable getItemSelectable()

Example

In the following code shows how to use ItemEvent.getItemSelectable() method.

import java.awt.BorderLayout;
import java.awt.ItemSelectable;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
/*from w w  w.j ava  2s. c o m*/
import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Main {

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