CSC 160-1 Lab 5-1: More on Events and Event Listeners

In this lab, you get to write some GUI programs that respond to events. We start with a simple program that allows the user to enter two strings into text fields and press a button to find out if the two strings are equal.

1.1 String Equality Check Program: the Frame

Start by writing a program that creates and displays the following user interface. The interface consists of a frame with a title, two text fields next to each other, and a single button below the two text fields. Write your code so that all variables are local to the main method.

I am using a pink background here, but your background can be any color.

1.2 Add a Border around the text fields

We can improve the looks of our user interface by adding a border that is 5 pixels all around to the panel that contains the two text fields at the top of the frame.

You can accomplish this with the statement

        textPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
    

This statement uses the setBorder() method of the Component class to put an empty border around the panel that contains the text field. The border has a width of 5 pixels on the left, top, right, and bottom of the panel.

1.3 Write a Listener class

The listener class must not be nested inside the main class. You will need to write the listener in such a way that it is passed two text fields at the time of creation. It stores the two text fields and compares their content when its action performed method is called. The event listener handler method will display an JOptionPane stating wheter the strings in the two text fields are equal. Here is a sample of how it should work:

Here is another sample:

1.4 Create a listener object and Attach it to the Button

You can do that following the examples in lecture. Test your complete program.

1.5 Add a Sum of Lengths Button

Modify the program by adding a second button with text

Sum of Lengths

and then modify your program so that whenever this button is clicked, it displays a message dialog showing the sum of the lengths of the string. For example

You may modify the same listener class to allow use of a single listener object added to both buttons, or you may write a separate listener class.

Due Date

Due Wedneday of of Week 5.