You are on page 1of 2

Introduction to GUI Using JOptionPane Dialogs*

How to run a simple program using JOptionPane Dialogs Instead of Console I/O (i.e. System.out.print() ) ?
Steps :1- Import the JOptionPane class.
2- Use showInputDialog() method to read Input (instead of Scanner).
3- Use method parseInt() in class Integer to convert the input to int or Use method
parseDouble() in class Double to convert the input to double.
4- Use showMessageDialog() method to display output (instead of System.out.print()).

Example:// this Program computes the Average of three ints. Using JOptionPane.
// Author: Fred Swartz
// Source: http://www.leepoint.net/notes-java/io/io-console/console-dialog-comparison.html

import javax.swing.JOptionPane;
public class Average {
public static void main(String[] args) {
//... Declare local variables;
int a, b, c;
int average;
String temp; // Temporary storage for JOptionPane input.
//... Read three numbers from dialog boxes.
temp = JOptionPane.showInputDialog(null, "First number"); //
a = Integer.parseInt(temp); // Convert String variable temp
temp = JOptionPane.showInputDialog(null, "Second number");
b = Integer.parseInt(temp); // Convert String variable temp
temp = JOptionPane.showInputDialog(null, "Third number");
c = Integer.parseInt(temp); // Convert String variable temp
//... Compute the average.
average = (a + b + c) / 3;
//... Display the average in a dialog box figure 2.
JOptionPane.showMessageDialog(null, "Average is " + average);
}
}

displays figure 1
to int.
to int.
to int.

Console Vs Dialog I/O


Console
Imports

import java.util.Scanner;
// For Scanner class.

Dialog
import javax.swing.JOptionPane;
// For JOptionPane class.

Initialization

Scanner S = new Scanner(System.in);

Output

System.out.println("Display this");

JOptionPane.showMessageDialog(null,
"Display this");

Line of text
input

String name;
System.out.print("Enter your name: ");
name = input.nextLine();

String name;
name=JOptionPane.showInputDialog(null,
"Enter your name");

Integer
input

System.out.print("Enter your age: ");


int age = input.nextInt();

String str;
str =JOptionPane.showInputDialog(null,
"Enter your age");
int age = Integer.parseInt(str);

None required.

* Source : http://www.leepoint.net/notes-java/io/io-console/console-dialog-comparison.html

You might also like