How to pre-select JComboBox item by index in Java?


The following is an example to pre-select JComboBox item by index in Java. Here, we have selected the 3rd item by default i.e. whenever the Swing program will run, the third item would be visible instead of the 1st.

Example

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class SwingDemo {
   public static void main(String[] args) {
      JPanel panel = new JPanel(new BorderLayout());
      String[] strArr = new String[] { "Laptop", "Mobile", "Desktop", "Tablet" };
      JComboBox<String> comboBox = new JComboBox<>(strArr);
      panel.add(comboBox, BorderLayout.NORTH);
      JTextArea text = new JTextArea(5, 5);
      panel.add(text, BorderLayout.CENTER);
      JButton btn = new JButton("Click");
      // selecting the index
      comboBox.setSelectedIndex(2);
      btn.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            text.setText((String) comboBox.getSelectedItem());
            comboBox.setSelectedIndex(0);
         }
      });
      panel.add(btn, BorderLayout.SOUTH);
      JFrame frame = new JFrame();
      frame.add(panel);
      frame.pack();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}

The output is as follows. The 3rd item is by default selected i.e. index 2:

Output

Here, you can check all the items:

Updated on: 30-Jul-2019

936 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements