Java Swing How to - Set selected item in JComboBox by index








Question

We would like to know how to set selected item in JComboBox by index.

Answer

//ww  w .j a v a 2  s .co m

import java.awt.FlowLayout;

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

public class Main {
  public static void main(String[] args) {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("JComboBox Test");
    frame.setLayout(new FlowLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    String[] selections = { "green", "red", "orange", "dark blue" };
    JComboBox comboBox = new JComboBox(selections);
    comboBox.setSelectedIndex(1);
    System.out.println(comboBox.getSelectedItem());
    frame.add(comboBox);
    frame.pack();
    frame.setVisible(true);
  }
}