Java Swing Tutorial - Java JComboBox.getItemCount()








Syntax

JComboBox.getItemCount() has the following syntax.

public int getItemCount()

Example

In the following code shows how to use JComboBox.getItemCount() method.

// w  w  w.  j  a v  a 2s . c om

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.util.Vector;

import javax.swing.AbstractAction;
import javax.swing.ComboBoxEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.plaf.ComboBoxUI;

public class Main extends JFrame {
  JComboBox jcb;

  Main(String title) {
    super(title);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel jp = new JPanel();

    Vector v = new Vector();
    v.add("A");
    v.add("B");
    v.add("C");

    jcb = new JComboBox(v);
    jcb.setEditable(true);

    jcb.getActionMap().put("selectNext", new DownAction());

    jp.setPreferredSize(new Dimension(200, 35));
    jp.add(jcb);
    getContentPane().add(jp);

    pack();
    setVisible(true);
  }

  public static void main(String[] args) {
    new Main("Binding Demo3");
  }
}

class DownAction extends AbstractAction {
  public void actionPerformed(ActionEvent e) {
    JComboBox jcb = (JComboBox) e.getSource();
    System.out.println("down action");
    ComboBoxUI ui = jcb.getUI();

    if (ui.isPopupVisible(jcb)) {
      int i = jcb.getSelectedIndex();
      if (i < jcb.getModel().getSize() - 1) {
        jcb.setSelectedIndex(i + 1);
        jcb.repaint();
      }
    } else {
      int nItems = jcb.getItemCount();

      ComboBoxEditor cbe = jcb.getEditor();

      String st; // Search text

      st = ((String) cbe.getItem()).toUpperCase();

      for (int i = 0; i < nItems; i++) {
        String item = ((String) jcb.getItemAt(i)).toUpperCase();

        if (item.startsWith(st)) {
          jcb.setSelectedIndex(i);
          break;
        }
      }

      ui.setPopupVisible(jcb, true);
    }
  }
}