Java program to set JComboBox in JOptionPane



In this article, we will explore how to create a graphical user interface (GUI) in Java using JComboBox and JOptionPane. The program will display a pop-up dialog that contains a drop-down list, allowing the user to select their favorite sport from a list. By default, one of the options will be pre-selected, but users can change the selection. 

Steps to set JComboBox in JOptionPane

Following are the steps to set JComboBox in JOptionPane ?

  • Create a JPanel by initializing a JPanel to hold the components.
  • Create a JComboBox by setting up a JComboBox with a list of sports.
  • Set the default selection and re-select "Cricket" as the default option.
  • Add JComboBox to JOptionPane by using JOptionPane.showMessageDialog to display the JComboBox in a dialog box.
  • The dialog box will pop up, allowing the user to select from the list of sports

Java program to set JComboBox in JOptionPane

The following is an example to set JComboBox in JOptionPane ?

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 ?

Code Explanation

First, a JPanel is created to serve as the container for the combo box. Then, a JComboBox is initialized with an array of sports. The default selected option is set to "Cricket" using comboBox.setSelectedIndex(1). Finally, the JComboBox is added to a JOptionPane, which will display the combo box in a dialog window. When the program runs, a pop-up window appears, allowing the user to select their favorite sport from the list.

Updated on: 2024-09-29T02:47:14+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements