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.

Don't forget the import statement

Before using JOptionPane, add this line to the top of your Java file (before the public class ... line).

 import javax.swing.*;

public class FooBar
{
    public static void main(String args[]) 
    {
        ...
    }
} 

This import statement brings in all of the information required for Java to know what a JOptionPane statement is and what it can do.

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 ways to output the outcomes of our programs.

 JOptionPane.showMessageDialog(null,"I love Winnipeg"); 

Don't forget to include the null value before the String you want to output.

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

In the next section you will learn how to use the JOptionPane to get input from the user.

Previous Page: Output using System.out. Next Page: Variables and Literals