Java Program to set JComboBox in JOptionPane


Let us first crate a ComboBox and add items to it −

Object[] sports = { "Football", "Cricket", "Squash", "Baseball", "Fencing", "Volleyball", "Basketball" };
JComboBox comboBox = new JComboBox(sports);

Now, add the combo box to the JOptionPane −

JOptionPane.showMessageDialog(null, comboBox, "Fav Sports", JOptionPane.QUESTION_MESSAGE);

The following is an example to set JComboBox in JOptionPane −

Example

package my;
import java.awt.GridBagLayout;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JPanel panel = new JPanel(new GridBagLayout());
      Object[] sports = { "Football", "Cricket", "Squash", "Baseball", "Fencing", "Volleyball", "Basketball" };
      JComboBox comboBox = new JComboBox(sports); comboBox.setSelectedIndex(1);
      JOptionPane.showMessageDialog(null, comboBox, "Fav Sports",
      JOptionPane.QUESTION_MESSAGE);
      panel.add(comboBox);
   }
}

Output

Be default, we have set index i.e. “Cricket”. You can select any of the options now from the ComboBox set −

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements