Java Program to set JComboBox in JOptionPane

Java 8Object Oriented ProgrammingProgramming

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 −

raja
Published on 04-Jun-2019 11:54:19
Advertisements