Difference between revisions of "Input using JOptionPane"

From CompSciWiki
Jump to: navigation, search
Line 1: Line 1:
 
{{1010Topic|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 input from a user.|Overview=Learn how to use input boxes to get input from the user.|Chapter_TOC=[[More About Computer Science]]}}
 
{{1010Topic|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 input from a user.|Overview=Learn how to use input boxes to get input from the user.|Chapter_TOC=[[More About Computer Science]]}}
==Input Box==
+
==Using an Input Box to Get Input From the User==
 
===Example===
 
===Example===
 
In this example we prompt the user to enter their name, store it in a variable (see section on variables), and print their name to the screen using System.out.
 
In this example we prompt the user to enter their name, store it in a variable (see section on variables), and print their name to the screen using System.out.

Revision as of 21:34, 20 March 2007

COMP 1010 Home > More About Computer Science


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 input 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 (see section on variables), and print their name to the screen 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);
  }
}


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 on the right of the equals sign pops up a dialog 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.

Input1.png


  • 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.