Big Java / Java Concepts Lab 12

Button Listeners


Write a program where the background color of the panel can be controlled with buttons. You will supply three buttons labeled Red, Yellow, and Green in a panel. And then, change the panel's background color depending on what button was clicked.

First, you will write a RedButtonListener class (it will be used as an inner class) whose actionPerformed method will be called whenever the "red" button is clicked.

Then, you will need to change the color of the panel background to Color.RED. You can change the background color of a panel using the setBackground method:


What is the code of your RedButtonListener class? Don't forget that it has to implement ActionListener.


Now, you will write the code needed to construct the three buttons, to construct the panel, to add the buttons to the panel, to add the panel to the frame and to show the frame.

The buttons won't do anything yet; listeners will be added in the next problem.

A sketch of how your program should look like has been provided for you:

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;

public class ColorChanger
    public static void main(String[] args)
       JFrame frame = new JFrame();

       // The buttons (one for each color)
       /* create the buttons here */

       // The panel that holds the user interface components
       final JPanel panel = new JPanel();
       /* add each button to the panel here, using the "panel.add" method */
       frame.add(panel); // adds the panel to the frame

       // The listener classes and listener objects will go here
       /* do not add listener code yet */

       // Show the frame
       frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);

    private static final int FRAME_WIDTH = 400;
    private static final int FRAME_HEIGHT = 100;

What is the code of your program?


Buttons generate action events. In order for your program to listen to them, you need to install action listeners. When the red button is clicked, you want to change the color to red. You will use the class you created in problem 1 for that purpose.

Enhance your program by adding the listener class and creating a listener object. Don't forget to add the following import statements in your program:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

Use the code you created in problem 2, and add the class and a listener for the red button where it is indicated. The "Red" button will change the color to red. The other two buttons will do nothing. You will add listeners to the other buttons in the next problem.

Remember that you will need to create a listener object and then add it to the red button using the addActionListener method.

Write and test your program. What is the code?


Now you will create listener classes and objects for the other two buttons, so that we can change the background color to yellow and green, respectively. You can copy and paste the code for the RedButtonListener class two times, and modify them to change the background color to yellow and green respectively.

Complete and test your program. Don't forget to create objects of the two new classes and add the listeners to the buttons.

What is the code for your program?


It is silly to write three separate classes to change the background to red, yellow, or blue. Instead, you can create one listener class (ButtonListener) that will handle events on all three buttons. The target color should be part of the state of the ButtonListener.

Implement the ButtonListener class, and then construct three objects of that class. Add these objects as listeners to the appropriate buttons:

ActionListener redListener = new ButtonListener(Color.RED);

What is the code for your program?


In your program, the panel variable is declared as final. Why?

Hint: If you don't know the answer, remove the final keyword, recompile, and study the error message.



In this program, you will to put a label into the frame. The code for a label is:

JLabel aLabel = new JLabel("The text goes here");

Write a graphical application in which the frame has a panel which has a label that displays the result of 10! (10 factorial).

Calculate the factorial using the following class:

public class FactorialGenerator
   public FactorialGenerator()
      count = 0;
      product = 1;
   public long getProduct() { return product; }
   public void next()
      product = product * count;
   public void next(int steps)
      for (int i = 1; i <= steps; i++)

   private int count;
   private long product;

What is the code for your program?


Now modify the program so that factorials are computed one step at a time, by clicking a button. The current product value should be displayed on the label.

You will need to create a button and add it to the panel.

Add the code to construct a button, panel, and frame. Place the button and the label on the panel; then, add the panel to the frame and show the frame.

Run the program. Of course, the button doesn't do anything.

What is the code for your program?


Now you will add a listener to the button so that it calls the next method of the FactorialGenerator and displays the product in the label. Modify the program as needed.

What is the code for your program?


Now add a text field so the user can enter an integer, namely the number of multiplication steps in each button click. Don't forget to modify your button listener so that it parses the text in the text field and calls the next(int steps) method.

What is the code for your program?

Mouse Events


A user interface component such as a panel can detect five types of mouse events. What are these events?


This exercise focuses on "entered" and "exited" mouse events. Write a mouse listener class that prints "Entered" and "Exited" to System.out when the mouse has entered or exited the frame. Do nothing for the other three mouse event types. Call your class EnterExitListener. Remember that you need to implement the MouseListener interface.

What is the code of your listener class?


Write a test program that tests your listener. You will need to add the listener to the frame using the addMouseListener method.

What is the code for your program?


Test your program. What must be done to show the messages "Entered" and "Exited"?


The previous program is a little dull. Make it more interesting. Rather than printing a message, change the background color of the frame. In the mouseEntered method, add the line


and in the mouseExited method, add the line


Make sure that your EnterExitListener is an inner class of the main method.

Compile and run your test program. When the mouse enters the frame, its background color should change to green. When the mouse leaves the frame, the background should turn red.

What is the code for your program?


Why must the EnterExitListener be an inner class?

Hint: If you are unsure, make EnterExitListener into a regular class, compile, and study the error message.



Write a component whose paintComponent method draws four lines:

1. From the point p to the top left corner

2. From the point p to the bottom left corner

3. From the point p to the top right corner

4. From the point p to the bottom right corner

Let p be the point with the coordinates (50, 100).

Call your component FourLineComponent.

Hint: Call getWidth() and getHeight() to get the x- and y-coordinates of the corner points.

If added to a frame and displayed, the component should look like this:

What is the code for your component class?


Now write a tester program that creates a frame, adds the component to the frame and displays it.

What is the code of your tester class?


Now enhance the program so that the point p can be changed by a mouse click.

Make an instance variable of type Point2D.Double. Add a method to the component that allows you to set the point, so that it can be changed during the program execution. If you did not have a point instance field (or x and y instance fields) in the component, you will need to modify the paintComponent method too, so that the lines all have one end in this point.

What is the code of your modified component class?


Write a MousePressListener class that implements the MouseListener interface. Its mousePressed method sets p to the point with x- and y-values of the mouse event.

Make sure that the mousePressed method calls the repaint() method on the component, after changing p. You can use the method getPoint to find out the position where the user clicked.

Add a MousePressListener as mouse listener to the tester program.

Run your program. Now you should be able to click the mouse and have the four lines meet at the point where you just clicked.

What is the code of your tester class?


Why is it important to call repaint in the mouse press listener? What would happen if you didn't call repaint?

Try it out. Comment out the call to repaint, recompile, and try your program again. What happens?