![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can we set JOptionPane with predefined selection in Java?
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
Advertisements