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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

References

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

上一篇: Maven and JUnit example
下一篇: Gradle and JUnit example
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号