Main Tutorials

Java Swing – JOptionPane showInputDialog example

This is a review of the showInputDialog() method of JOptionPane Class. With this method we can prompt the user for input while customizing our dialog window. The showConfirmDialog returns either String or Object and can be called using the following combinations of parameters:

  • Object (returns String) – Shows a question-message dialog requesting input from the user.
  • Object, Object (returns String) – Shows a question-message dialog requesting input from the user with the input value initialized.
  • Component, Object (returns String) – Shows a question-message dialog requesting input from the user. Returns the input as String. The Component determines the Frame in which the dialog is displayed; if null, or if the parentComponent has no Frame, a default Frame is used.
  • Component, Object, Object (returns String) – Same as above. The only difference is that the input field has an initial value set through the last Object parameter.
  • Component, Object, String, int (returns String) – Shows a dialog requesting input from the user. The dialog has a title set through the String parameter and a MessageType set through the int parameter. The different MessageTypes for JOptionPane, are:
    • ERROR_MESSAGE
    • INFORMATION_MESSAGE
    • WARNING_MESSAGE
    • QUESTION_MESSAGE
    • PLAIN_MESSAGE
  • Component, Object, String, int, Icon, Object[], Object (returns Object) – Prompts the user for input in a blocking dialog where the initial selection, possible selections, and all other options can be specified. The Icon (if not null) is displayed inside the dialog and overrides the default MessageType icon.

1. Object – The simplest way to get user input

Example of a question-message dialog that gets user input as String:

SimpleInputDialog1.java

package com.mkyong.inputDialog;

import javax.swing.JOptionPane;

public class SimpleInputDialog1 {

    public static void main(String[] args){

        String m = JOptionPane.showInputDialog("Anyone there?");
        System.out.println(m);

    }

}

Output:

swing-showinputdialog-3a

When you type “Hellooooo!!!!” in the input field and click “OK”


Hellooooo!!!!

2. Object & Object – Setting an initial value over the input

Example of a question-message dialog with an initial value that gets user input as String:

SimpleInputDialog2.java

package com.mkyong.inputDialog;

import javax.swing.JOptionPane;

public class SimpleInputDialog2 {

    public static void main(String[] args){

        String m = JOptionPane.showInputDialog("Anyone there?", 42);
        System.out.println(m);

    }

}

Output:

swing-showinputdialog-3b

3. Component & Object – Setting the dialog in a parent Component

If we set the Component to null, the result will be the same with number 1. For this example we will create a JFrame to put our dialog in. The frame closes unless the user types something in the field:

InputDialogInFrame.java

package com.mkyong.inputDialog;

import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class InputDialogInFrame extends JFrame{

    public InputDialogInFrame() {

        getContentPane().setBackground(Color.DARK_GRAY);
        setTitle("Input Dialog in Frame");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setResizable(false);
        setSize(400, 300);
        getContentPane().setLayout(null);

    }

    private void closeIt(){

        this.getContentPane().setVisible(false);
        this.dispose();

    }

    public static void main(String[] args){

        InputDialogInFrame frame = new InputDialogInFrame();
        String m = JOptionPane.showInputDialog(frame, "Anyone there?");
        if(m.isEmpty()){
            frame.closeIt();
        }

    }

}

Output:

swing-showinputdialog-3c

4. Component, Object & Object – Setting the dialog in a parent Component with an initial value

If we set the Component to null, the result will be the same with number 2. For this example we will change slightly the code from number 3:

InputDialogInFrame.java

package com.mkyong.inputDialog;

import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class InputDialogInFrame extends JFrame{

    public InputDialogInFrame() {

        getContentPane().setBackground(Color.DARK_GRAY);
        setTitle("Input Dialog in Frame");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setResizable(false);
        setSize(400, 300);
        getContentPane().setLayout(null);

    }

    private void closeIt(){

        this.getContentPane().setVisible(false);
        this.dispose();

    }

    public static void main(String[] args){

        InputDialogInFrame frame = new InputDialogInFrame();
        String m = JOptionPane.showInputDialog(frame, "Anyone there?", 42);
        if(m.isEmpty() || m.equals("42")){
            frame.closeIt();
        }

    }

}

Output:

swing-showinputdialog-3d

5. Component, Object, String & int – Let us give our input dialog a title and choose the MessageType

An example of an information-message using the default icon through JOptionPane.INFORMATION_MESSAGE:

SimpleInputDialog5.java

package com.mkyong.inputDialog;

import javax.swing.JOptionPane;

public class SimpleInputDialog5 {

    public static void main(String[] args){

        String m = JOptionPane.showInputDialog(null, "Broccoli is tasty!", 
                "Green dinner", JOptionPane.INFORMATION_MESSAGE);

        System.out.println(m);

    }

}

Output:

swing-showinputdialog-3e

6. Component, Object, String, int, Icon, Object[] & Object – Input dialog with predefined options

6.1 In this example we provide the user with a set of options to choose from. The different options appear in a form of a drop down menu with a selected initial value:

InputDialog6a.java

package com.mkyong.inputDialog;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

public class InputDialog6a {

    public static void main(String[] args) {

        String[] options = {"I adore turtles", "Yes", "Maybe", "Urm...", "No", "Hate them"};
        ImageIcon icon = new ImageIcon("src/images/turtle32.png");
        String n = (String)JOptionPane.showInputDialog(null, "Do you like turtles??", 
                "I like turtles", JOptionPane.QUESTION_MESSAGE, icon, options, options[2]);
        System.out.println(n);

    }

}

Output:

swing-showinputdialog-3f

When you select the option “I adore turtles” and click “OK”


I adore turtles

6.2 An example using array of Integers:

InputDialog6b.java

package com.mkyong.inputDialog;

import javax.swing.JOptionPane;

public class InputDialog6b {

    public static void main(String[] args) {

        Integer[] options = {2, 3, 5, 7, 9, 11};
        int n = (Integer)JOptionPane.showInputDialog(null, "Pick a number that is not prime:", 
                "Prime numbers", JOptionPane.QUESTION_MESSAGE, null, options, options[2]);
        System.out.println(n);

    }

}

Output:

swing-showinputdialog-3g

6.3 An example where we take advantage of the dynamics the Object array and the Object return type of the method:

InputDialog6c.java

package com.mkyong.inputDialog;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

public class InputDialog6c {

    public static void main(String[] args) {

        Object[] options = {2, "No", 5.6, true};
        Object l = JOptionPane.showInputDialog(null, "Just pick something already!", 
                "Mix & Match", JOptionPane.ERROR_MESSAGE, null, options, options[0]);

        if(l instanceof Integer){
            System.out.println("You picked an Integer!");
        }else if(l instanceof String){
            System.out.println("You picked a String!");
        }else if(l instanceof Double){
            System.out.println("You picked a Double!");
        }else if(l instanceof Boolean){
            System.out.println("You picked a Boolean!");
        }

    }

}

Output:

swing-showinputdialog-3h

When “2” is selected and user clicks “OK”:


You picked an Integer!

When “No” is selected and user clicks “OK”:


You picked a String!

When “5.6” is selected and user clicks “OK”:


You picked a Double!

When “true” is selected and user clicks “OK”:


You picked a Boolean!

7. A more advanced example

On all previous examples a String was used in the place of Object; for this example we will use a JPanel in the place of the Object. The JPanel is customized and has a JLabel added to it. We are also manipulating the size of the OptionPane using a call to UIManager.

InputDialogPanel.java

package com.mkyong.inputDialog;

import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;

public class InputDialogPanel {

    public static void main(String[] args) {

        JPanel panel = new JPanel();
        panel.setBackground(new Color(0, 0, 0));
        panel.setSize(new Dimension(250, 32));
        panel.setLayout(null);

        JLabel label = new JLabel("It's your choice! :)");
        label.setForeground(new Color(255, 255, 0));
        label.setHorizontalAlignment(SwingConstants.CENTER);
        label.setFont(new Font("Arial", Font.BOLD, 11));
        label.setBounds(0, 0, 250, 32);
        panel.add(label);

        UIManager.put("OptionPane.minimumSize",new Dimension(270, 120));

        Object[] options = {2, "No", 5.6, true};
        Object l = JOptionPane.showInputDialog(null, panel, 
                "Mix & Match", JOptionPane.PLAIN_MESSAGE, null, options, options[3]);

        if(l instanceof Integer){
            System.out.println("You picked an Integer!");
        }else if(l instanceof String){
            System.out.println("You picked a String!");
        }else if(l instanceof Double){
            System.out.println("You picked a Double!");
        }else if(l instanceof Boolean){
            System.out.println("You picked a Boolean!");
        }

    }

}

Output:

swing-showinputdialog-3i

References

  1. How to Make Dialogs
  2. Class JOption Pane – Java 8 API
  3. Constant Field Values

About Author

author image
Marilena Panagiotidou is a senior at University of the Aegean, in the department of Information and Communication Systems Engineering. She is passionate about programming in a wide range of languages. You can contact her at [email protected] or through her LinkedIn.

Comments

Subscribe
Notify of
11 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Daniela
5 years ago

Loved it !

Anwar
4 years ago

Superb awesome,thank you so much

Andrés Maximiliano Mastracchio
4 years ago

Thanks a lot, Marilena! this post is very handful! Helped me understand a coding issue I was having

Armaan
4 years ago

I am a 9th grader studing in Mumbai,India. For my IGCSE Computer Science project this year, your gudie came in handy. It is just perfect and extremely helpful, not to forget, user friendly. Thank you so much Marilena pls make more tutorials like these!

Paty
2 years ago

Thank u!

Nimanthi
2 years ago

Thank you i fixed my error.ths is well help to me.

mohammed siraj
3 years ago

thanks

Ella
4 years ago

Is it possible to input 3 variables in one input dialog? my prof ask us to code a program that input the month date and year in one input dialog.

Ana Salazar
5 years ago

6.1 is not working. I’m using eclipse ide.

LOL
4 years ago
Reply to  Ana Salazar

All IDE’s work. You should look for the error in the code.