Java JComboBox get selected value

Description

Java JComboBox get selected value


import java.awt.FlowLayout;

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

class Demo extends JPanel {
  public Demo() {
    JComboBox<String> jcb;
    String options[] = { "CSS", "HTML", "Java", "Javascript" };
    setLayout(new FlowLayout());
    jcb = new JComboBox<String>(options);
    /*w  w  w  .ja  v a 2s.c o m*/
    jcb.addItem("A");
    jcb.addItem("B");
    jcb.addItem("C");
    
    
    add(jcb);

    String v = getComboBoxValue(jcb);
    System.out.println(v);
    
  }
  
  /**
   * Returns the currently selected combobox value.  If there
   * is no value, it return the empty string.
   */
  public static String getComboBoxValue(JComboBox comboBox) {
      if (comboBox.getSelectedItem() != null) {
          return comboBox.getSelectedItem().toString();
      } else {
          return "";
      }
  }  
}

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