Java: Dialog Box Input-Output

This is very similar to the second program, but it gets input from the user. The new statements are described below.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
// ThirdProgram.java
// Michael Maus, 25 August 2004
// This program gets a string from a dialog box.

import javax.swing.*;

public class ThirdProgram {
    
    public static void main(String[] args) {
        String name;  // A local variable to hold the name.
        
        name = JOptionPane.showInputDialog(null, "What's your name, Earthling");
        
        JOptionPane.showMessageDialog(null, "Take me to your leader, " + name);
        
        System.exit(0);  // Stop GUI program
    }
}
Line 10 - Declaring a local variable.
This tells the compiler to reserve some memory to hold a String. It's going to hold the user's name, so we called the variable "name".
Line 12 - Asking the user for a String.
Another type of dialog box that JOptionPane will show can get input from the user. Call the showInputDialog method for this. It will return a string that can be stored into a variable. Here we save it in the variable name.
Line 14 - Putting two strings together (concatenation)
This is similar to the previous program, but it puts two strings together to build a bigger string. The plus sign (+) will join two strings to make a new string.