How to Show the Input Dialog in Java


In this example we will show the method to show the input dialog in Java.

Source Code

1)The simplest way to get user input

package com.beginner.examples;

import javax.swing.JOptionPane;

public class DialogExample1 {

	public static void main(String[] args) {

		String m = JOptionPane.showInputDialog("Are you ok?");
        //System.out.println(m);
        System.out.println("Done!");
    }
}

Output:

Done!

2)Setting an initial value over the input

package com.beginner.examples;

import javax.swing.JOptionPane;

public class DialogExample2 {

	public static void main(String[] args) {

		String n = JOptionPane.showInputDialog("Are you ok?","I'm fine.");
        //System.out.println(n);
        System.out.println("Done!");
    }
}

Output:

Done!

3)Input dialog with predefined options

package com.beginner.examples;

import javax.swing.JOptionPane;

public class DialogExample3 {

	public static void main(String[] args) {

		String[] options = {"I'm fine.","No.I don't feel good."};
		String n = (String) JOptionPane.showInputDialog(null, "Are you ok?", 
                "", JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
        //System.out.println(n);
        System.out.println("Done!");
    }
}

Output:

Done!

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments