CSC 160-2 Lab 6-1 More on GUI Programs and Event Listeners

Overview of the lab assignment

In this lab, you will gain further experience writing event listeners for GUI program. You are going to write a program that presents the user with a user interface that looks like this:


The program will work as follows. When the user clicks on the Randomize button, the program will fill the text fields random integers in the range 0 - 99. At that point, the user interface will look something like this:


When the user presses the Max Min button, the program will highlight one of the text fields that has a least value in the text fields, and will also highlight one of the text fields that has a greatest value. The least value should be highlighted in one color (say YELLOW) while the greatest value is highlighted on a second color (say BLUE).


Each time the user presses the Randomize button, all highlights are removed and new random numbers are generated into the text fields. Then when the MaxMin button is clicked, new least and greatest values are highlighted:

Randomized2 Randomized2

Step 1: Build the User Interface

Specifically, the program displays a user interface with ten text fields at the top of the frame, and two buttons with labels as shown, at the bottom of the frame. The user interface should use a GridLayout for the ten text fields at the top. Go ahead and write a program that builds this user interface and run it. It should display as shown here.


Step 2: Write the Event Listener

Write a separate listener class (It should not be nested in any other class). You should use a single listener that will handle events for both buttons.

Note that the event listener class will need access to the array of text fields: set it up so it has a constructor that accepts such an array as parameter.

The best way to proceed is have the listener class have two array variables.

int [ ] numbers = new int [10];
JTextField [] textFields;

The numbers array will hold the random integers generated, while the textFields array store a link to the text fields in the user interface.

To create the array of random integers, use an object of the Random class. Here is an example of code that creates a random integer in the range 0-99:

Random randy = new Random();  // Random number generator object
// Get nonnegative integer less than 100 from the random number generator
int x = randy.nextInt(100);   

Hint: The best way to proceed is to generate the random numbers into the numbers array and then copy them into the text fields whenever the Randomize button is clicked. When the MaxMin button is clicked, use the numbers array to find the positions of the least and greatest values, and then highlight the text fields at those positions.

Due Date

Friday of Week 6.