Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Nancy Den

To display the first element in a JComboBox, use the getSelectedIndex():

comboBox.setSelectedIndex(0);

The following is an example to display the first element in a JComboBox in Java:

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");
      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 displaying the first item:

Output

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.