Input using JOptionPane

From CompSciWiki
Revision as of 21:16, 21 March 2007 by Umhieb34 (Talk | contribs)

Jump to: navigation, search

COMP 1010 Home > Your First Java Program


Introduction

JOptionPane gives you the ability to create dialogs. A dialog is a window that pops up and either displays a message or requests input from a user. This section will show you how to use JOptionPane to get a string from a user.

   

{{{Body}}}

Using an Input Box to Get Input From the User

Example

In this example we prompt the user to enter their name, store it in a variable, and greet them with their name using System.out.

import javax.swing.JOptionPane;

public class Input
{
  public static void main(String args[]) 
  {
    String name;
    
    name = JOptionPane.showInputDialog("Enter your name:");

    System.out.println("Hello " + name);
  }
}
Input1.png

We will now describe the important lines in this program:

  • import javax.swing.JOptionPane;

JOptionPane is part of the javax.swing package. To give our class access to JOptionPane we have to use the import statement.

  • name = JOptionPane.showInputDialog("Enter your name:");

The method showInputDialog pops up a dialog (pictured to the right) with the message "Enter your name:" and an input box for the user to enter their name. Once the user enters their name and hits the OK button, the method returns with the string that was entered in the input box. This string is stored in the name variable.


  • System.out.println("Hello " + name);

Now that we have stored the user's name, we can use System.out.println to print "Hello name", where name is what the user entered in the input box.