- Trending Categories
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
How to use JOptionPane with Array Elements in Java?
Let us first create and array and add elements −
String[] sports = { "Football", "Cricket", "Squash", "Baseball", "Fencing", "Volleyball", "Basketball" };
Now, set the above array elements to the JOptionPane −
String res = (String) JOptionPane.showInputDialog(null, "Which sports you play the most?", "Sports", JOptionPane.PLAIN_MESSAGE, null, sports, sports[0]);
Above, we have also set the initial value i.e. sports(0).
The following is an example to use JOptionPane with array elements in Java −
Example
package my; import javax.swing.JOptionPane; public class SwingDemo { public static void main(String[] args) { String[] sports = { "Football", "Cricket", "Squash", "Baseball", "Fencing", "Volleyball", "Basketball" }; String res = (String) JOptionPane.showInputDialog(null, "Which sports you play the most?", "Sports", JOptionPane.PLAIN_MESSAGE, null, sports, sports[0]); switch (res) { case "Football": System.out.println("I Love Football"); break; case "Cricket": System.out.println("I Love Cricket"); break; case "Squash": System.out.println("I Love Squash"); break; case "Baseball": System.out.println("I Love Baseball"); break; case "Fencing": System.out.println("I Love Fencing"); break; case "Volleyball": System.out.println("I Love Volleyball"); break; case "Basketball": System.out.println("I Love Basketball"); break; } } }
Output
Now select any of the item from above and click OK to display the selected item in the Console. We selected “Volleyball” −
The option selected above visible in Console −
- Related Articles
- Can we set JOptionPane with predefined selection in Java?
- Java Program to set JComboBox in JOptionPane
- Customize the JOptionPane layout with updated color and image in Java
- How to replace elements in array with elements of another array in JavaScript?
- How to Alter Two Array Elements in Java
- How to make JOptionPane to handle Yes, No and Closed buttons in Java?
- How to sort Java array elements in ascending order?
- How to make elements of array immutable in Java?
- How to Find Single Digit Array Elements in Java?
- Java Program to set an icon for JOptionPane
- Add multiple number input fields with JOptionPane and display the sum in Console with Java
- How to fetch elements with iterator in Java?
- How to count unique elements in the array using java?
- How to remove duplicate elements of an array in java?
- How to add elements to the midpoint of an array in Java?

Advertisements