Java JComboBox search value

Description

Java JComboBox search value



import java.awt.FlowLayout;

import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

class Demo extends JPanel {
  public Demo() {
    /*from w w w.  jav a 2 s  .  c  om*/
    String options[] = { "CSS", "HTML", "Java", "Javascript" };
    setLayout(new FlowLayout());
    JComboBox<String> jcb = new JComboBox<String>(options);
    jcb.setEditable(true);
    add(jcb);
    boolean b = containsValue(jcb,"Java");
    System.out.println(b);
  }
  /**
   * @param comboBox
   * @param value
   * @return if the comboBox contains the specified value
   */
  public static boolean containsValue(JComboBox<String> comboBox, String value) {
      ComboBoxModel<String> model = comboBox.getModel();
      int size = model.getSize();
      for (int i = 0; i < size; i++) {
          Object element = model.getElementAt(i);
          if (element.equals(value)) {
              return true;
          }
      }
      return false;
  }
}

public class Main {
  public static void main(String[] args) {
    Demo panel = new Demo();
    JFrame application = new JFrame();
    application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    application.add(panel);
    application.setSize(250, 250);
    application.setVisible(true);
  }
}



PreviousNext

Related