Java Swing How to - Show the first element in a JComboBox








Question

We would like to know how to show the first element in a JComboBox.

Answer

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*  w w w .  j a  va2  s  . co  m*/
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class Main {
  public static void main(String[] args) {
    JPanel panel = new JPanel(new BorderLayout());
    String[] values = new String[] { "One", "Two", "Three" };
    JComboBox<String> comboBox = new JComboBox<>(values);
    panel.add(comboBox, BorderLayout.NORTH);
    JTextArea textArea = new JTextArea(2, 2);
    panel.add(textArea, BorderLayout.CENTER);
    JButton button = new JButton("Action");
    button.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        textArea.setText((String) comboBox.getSelectedItem());
        comboBox.setSelectedIndex(0);
      }
    });
    panel.add(button, BorderLayout.SOUTH);
    JFrame frame = new JFrame();
    frame.add(panel);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
}