Can we set JOptionPane with predefined selection in Java?

Java 8Object Oriented ProgrammingProgramming

For predefined selection, use the setSelectedIndex() method, wherein you need to set the index of the item you want to be visible first.

Let’s say the following is our aComboBox with elements −

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

Now, set the initial selection with the index of the item −

comboBox.setSelectedIndex(3);

The following is an example to set JOptionPane with predefined selection in Java −

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);
      // initial selection
      comboBox.setSelectedIndex(3);
      JOptionPane.showMessageDialog(null, comboBox, "Fav Sports",
      JOptionPane.QUESTION_MESSAGE);
      panel.add(comboBox);
   }
}

Output

raja
Published on 04-Jun-2019 08:34:16
Advertisements