CSC 160 Lab 4-2

GUI Data Input and Output, and Introduction to Event Listeners

Displaying Information with JOptionPane

So far we have used the console to display information to the user. For example, we can display a string like this:

        System.out.print("How are you?");
    

We typically do not use the console in a GUI application (Although it is possible to do so). One way to display a message to the user in a GUI application is to use one of the methods of the JOptionPane class.

        static void showMessageDialog(Component parentComponent, Object message)
    

This method shows a dialog box, which is a component that is used by the program to talk to (carry out a dialog with) the user. There are different types of dialog boxes. This method displays a message dialog, which simply display information, or a message to the user.

As you can see, this method takes two parameters. The first parameter is GUI component called called the parent of the dialog. This is another user interface component on which the dialog will be centered. You can use null to center the dialog on the entire screen. If you have a JFrame for your program, you can use it as the parent.

The second parameter is any object that you want to display. For example, to display a dialog that shows the message "How are you?" centered on the screen, write a program with the main method:

    public static void main(String[] args)
    {
        JOptionPane.showMessageDialog(null,  "How are you?");
    }
    

This will display as

Note that the above dialog has a default title of "Message". You often want to specify your own title.

Another version of showMessageDialog is

        static void showMessageDialog(Component parentComponent, Object message, String title, int messageType)
    

This version also takes a title for the dialog box, and an integer for the message type. The integers that specify the message type must be one of the following static int fields of the JOptionPane class:

         JOptionPane.PLAIN_MESSAGE
         JOptionPane.QUESTIOM_MESSAGE
         JOptionPane.INFORMATION_MESSAGE
         JOptionPane.WARNING_MESSAGE
    

Note that the title must be a String object, but the message can be any Object.

Exercise 1

Modify the previous program to use this second method and display the following dialog. You will have to figure out what values to use for the title and messageType parameters.

Reading Strings with JOptionPane

So far we have been using the next() and nextLine() methods of the Scanner class to read strings. GUI applications do normally use a scanner to read data, so we need something else.

The JOptionPane class has methods that display a dialog that prompts the user to enter a string into a text field, and returns the string entered by the user.

        static String 	showInputDialog(Object message)
        static String 	showInputDialog(Component parentComponent, Object message)
        static String 	showInputDialog(Component parentComponent, Object message, String title, int messageType)
    

These three methods allow you to specify a message that tells the user what is to be entered. For example, the code

public static void main(String[] args)
    {
        // Ask user for their name
        String name;
        name = JOptionPane.showInputDialog(null,  
                                  "What is your name?", 
                                  "Name Dialog", 
                                  JOptionPane.QUESTION_MESSAGE);

        // Display a message dialog to greet the user
        JOptionPane.showMessageDialog(null, "Hello " + name);
    }
    

will use an input dialog to get the user's name, and then use a message dialog to greet the user.

Exercise 2

Write a program that displays a succession of three dialogs. The first dialog asks the user for their first name, the second dialog asks the user for their last name, and the third dialog greets the user by their full name.

Reading Numbers With JOptionPane

Console applications use nextInt() of the Scanner class to read integers from System.in. GUI applications do not normally use System.in. To read an integer, you must have the user enter the integer as a string, and then convert the string to an integer.

There is a class called Integer that contains many static methods for working with values of type int. Among those methods is the following:

        static int parseInt(String s)
    

This method takes a string that represents an integer, for example "367", and returns the equivalent integer value, 367. To read an integer, use a JOptionPane.showInputDialog() method to read the integer, in string form, and then convert the string to an int using Integer.parseInt(). Here is an example that reads in an integer, squares it, and displays the square:

public static void main(String[] args)
    {
        String numberStr;
        numberStr = JOptionPane.showInputDialog(null,  
                                  "Enter an integer", 
                                  "Number Entry Dialog", 
                                  JOptionPane.PLAIN_MESSAGE);
        
        // Convert the number string to an int
        int number;
        number = Integer.parseInt(numberStr);
        
        // Display the square        
        JOptionPane.showMessageDialog(null, number * number, 
                                      "The square of " + number, 
                                      JOptionPane.INFORMATION_MESSAGE);
    }
    

Exercise 3

Write a program that asks the user to enter two numbers in two separate input dialogs, and then displays the sum and product of those two numbers in a message dialog:

Using Event Listeners

Let us write a simple program that has a JButton in a JFrame. The user interface will consist of a JFrame with a FlowLayout and a button in the JFrame.

The program looks like this:

package lab4_2part1;

import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;

public class Lab4_2Part1 
{  
    public static void main(String[] args)
    {
        // Create a JFrame
        JFrame frame = new JFrame("Button Clicker");
        
        // Set a FlowLayout in the frame
        frame.setLayout(new FlowLayout());
        
        // Create a button
        JButton button = new JButton("Click Me!");
        
        // Add the button to the frame
        frame.add(button);
        
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 100);
        frame.setVisible(true);
    }
}
    

Run this program to make sure it works.

Now we want to create an ActionListener object to add to the button. That way, when the button is clicked, the actonPerformed method in the listener will be called. The listener method will display a message dialog that says "You clicked me!".

First, we have to write the class that will serve as a pattern for the listener. Add a second class to your program, like this:

class MyListener implements ActionListener
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        JOptionPane.showMessageDialog(null, 
                "You Clicked Me!", "Click Message",
                JOptionPane.INFORMATION_MESSAGE);
    }    
}

    

This class goes in the same file, either after or before the main class. For example, you can put it after the main class like this:

package lab4_2part1;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Lab4_2Part1 
{  
    public static void main(String[] args)
    {
        // Create a JFrame
        JFrame frame = new JFrame("Button Clicker");
        
        // Set a FlowLayout in the frame
        frame.setLayout(new FlowLayout());
        
        // Create a button
        JButton button = new JButton("Click Me!");
        
        // Add the button to the frame
        frame.add(button);
        
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 100);
        frame.setVisible(true);
    }
}

class MyListener implements ActionListener
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        JOptionPane.showMessageDialog(null, 
                "You Clicked Me!", "Click Message",
                JOptionPane.INFORMATION_MESSAGE);
    }    
}

    

We are almost done! Next, we need to create an action listener object and then add it to the button so it is the listener for clicks on the button, like this.

        // Create a listener object and addd it to the button
        ActionListener listener = new MyListener();
        button.addActionListener(listener);
    

This code goes in the main method of the main class, just after the code that creates the button.

When you click the button, the option pane dialog should be displayed as shown below.

Note

This lab does not have to be handed in. However, its contents will be on the midterm next week.