Input using JOptionPane

From CompSciWiki
Jump to: navigation, search

COMP 1010 Home > Java Fundamentals


Introduction

You've used JOptionPane to output a message using JOptionPane.showMessageDialog. Now let's focus on using JOptionPane to get information from the user, using JOptionPane.showInputDialog.

Also, remember JOptionPane.showInputDialog also requires the import statement import javax.swing.JOptionPane; at the top of your program.

showInputDialog

An input dialog requests information from the user and stores it for use in the program.

Code

 import javax.swing.JOptionPane;
public class InputDialog {
	public static void main(String args[]){
		String message; // This will hold the result of your input.
		message = JOptionPane.showInputDialog("Enter your name");
	}
} 

Output

ShowInputDialog.png

How It Works

The showInputDialog("Enter your name") method creates a dialog with the message "Enter your name" and provides a text box for users to enter input. The contents of the text box is returned as a String after the user presses OK. The String is stored in the variable message in the code example above.

At this point you don't know much about variables. That will change quickly! But for now just think of a variables of a place in the computer's memory where you can store a value. It is significant that the variables message has the word String in front of it. That states that message will store a String value. This works well, since JOptionPane.showInputDialog will store the user's input in the form of a String.


Summary

In this section you have learned how to collect user information using JOptionPane. At this point you can input, output, and so you can write some more interesting programs. In the next section you will learn how to get user input from the command line.

Previous Page: Output using JOptionPane Next Page: Input using Scanner