Prev: none | Next: JOptionPane - More Dialogs

Java: JOptionPane - Simple Dialogs

Here are two useful static methods from javax.swing.JOptionPane that allow you to easily create dialog boxes for input and output. The Java API documentation has many more JOptionPane options, but these are sufficient for many uses. In the code below userInput and text are Strings.

ValueMethod call
userInput =  JOptionPane.showInputDialog(component, text);
JOptionPane.showMessageDialog(component, text);

Use null for the component parameter if you don't have a window

The dialog box will be centered over the component given in the first parameter. Typically you would give the window over which it should be centered. If your program doesn't have a window, you may simply write null, in which case the dialog box will be centered on the screen.

Example

This program produces the dialog boxes below.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
// File: joptionpane-examples/JOptionPaneTest1.java
// Description: JOptionPane example.
// Author: Fred Swartz
// Date:   31 Jan 2005

import javax.swing.JOptionPane;

public class JOptionPaneTest1 {
    public static void main(String[] args) {
        String ans;
        ans = JOptionPane.showInputDialog(null, "Speed in miles per hour?");
        double mph = Double.parseDouble(ans);
        double kph = 1.621 * mph;
        JOptionPane.showMessageDialog(null, "KPH = " + kph);

        System.exit(0);
    }
}

Notes

Line 11
This line displays a String, an input text field (JTextField), and OK and CANCEL buttons. If the user presses the OK button, the string in the text field is returned. If the user didn't type anything, the string "" is returned. If the user presses the CANCEL button, null is returned.

Because this call returns a String, it's necessary in the next line to convert it into a double to do the arithmetic calculation.

Line 14
This line displays a String and an OK button. In this call the String formed by concatenating a String literal with a number. When a String is concatenated with anything, that other operand is converted to a String by Java, then the two are put together into a new String.