Mega Code Archive

 
Categories / Java Tutorial / Swing
 

Set selected index

You can set an initial selection (s) by using the setSelectedIndex and setSelectedIndices methods (the indexing is zero-based, so index 0 refers to the first option in the JList). public void setSelectedIndex (int index) public void setSelectedIndices (int[] indices) import java.awt.FlowLayout; import javax.swing.JComboBox; import javax.swing.JFrame; public class JComboBoxTest {   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);   } }