How to create input Pop-Ups (Dialog) and get input from user in Java?

Java 8Object Oriented ProgrammingProgramming

Use the JOptionPane.showInputDialog() to get input from user in a dialog box like “Which sports you play the most”, “What is your name”, etc. The following is an example to create input Pop-Ups (Dialog) and get input from user −


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");
         case "Cricket" −
            System.out.println("I Love Cricket");
         case "Squash" −
            System.out.println("I Love Squash");
         case "Baseball" −
            System.out.println("I Love Baseball");
         case "Fencing" −
            System.out.println("I Love Fencing");
         case "Volleyball" −
            System.out.println("I Love Volleyball");
         case "Basketball" −
            System.out.println("I Love Basketball");


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 −

Published on 04-Jun-2019 12:11:25