Input/Output using JOptionPane

From CompSciWiki
Jump to: navigation, search

COMP 1010 Home > Java Fundamentals


Introduction

Now you know how to output a String in the windows console using System.out. Now, here's another output strategy: JOptionPane[[1]] 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. It is the Java equivalent of a message box.

Message Dialog Overview

A dialog providing a message to the user. The dialogs can be either a warning, information, error, question or plain. You will typically use this when you need to inform the user of something, but don't need any information or confirmation back from them. In COMP 1010 we'll use dialog as another way to output the result of our programs.

Here is an example of a simple dialog:

Code

import javax.swing.*;
public class InputDialog {
	public static void main(String args[]){
	    JOptionPane.showMessageDialog(null, "I love Winnipeg");
	}
}

Result

Lovewinnipeg.png

More on JOptionPane

The first argument of null tells the JOptionPane to display the message in a default frame. You don't need to worry about this since it is beyond the scope of the course. The second argument is, as noted, the title of the dialog and the final argument is a constant telling the JOptionPane what format and icon to use for your message. Only two examples of the 5 possible are shown, however the syntax is identical. You can read more about JOptionPane in the Gaddis textbook.

JOptionPane.showMessageDialog(null, "This is the information for the user.", "Title of Dialog Box", JOptionPane.INFORMATION_MESSAGE);
Message.jpg
JOptionPane.showMessageDialog(null, "This is the same, but is a WARNING!", "Title of Dialog", JOptionPane.WARNING_MESSAGE);
Warning.jpg

Notice that with a showMessageDialog you do not need to capture a result from the user's action, since we are only displaying a message to the user. In the next section you will learn how to get information back from the user.


Summary

In this section you have learned how to display a message box to the user using JOptionPane. Be careful when coding this, don't forget to add the first null argument. Now, let's learn how to get information back from the user also using JOptionPane.

Previous Page: Output using System.out. Next Page: Input using JOptionPane