首页javajcomboboxJava Swing - 如何通过索引在JComboBox中设置所选项

Java Swing - 如何通过索引在JComboBox中设置所选项

我们想知道如何通过索引在JComboBox中设置所选项。

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