import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


/**
  set up and display a frame with three buttons

  Adapted from "Core Java" text, 11th edition, Chapter 10

  @author Cay Horstmann
  @author adapted by Sharon Tuttle
  @version 2021-09-20
*/

public class ButtonTest
{
    /**
        creates a simple 3-button frame

        @param args not used here
     */

    public static void main(String[] args)
    {
	EventQueue.invokeLater(
	    () ->
	       {
		   ButtonFrame frame = new ButtonFrame();
		   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		   frame.setVisible(true);
	       } );
    }
}

/**
     A frame with a button panel
 */

class ButtonFrame extends JFrame
{
    // data fields

    private JPanel buttonPanel;
    
    private static final int DEFAULT_WIDTH = 300;
    private static final int DEFAULT_HEIGHT = 200;

    
    /**
        construct a button-panel frame instance
    */

    public ButtonFrame()
    {
	setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
	setTitle("Button Test");

        // create some buttons

	JButton yellowButton = new JButton("Yellow");
	JButton blueButton = new JButton("Blue");
	JButton redButton = new JButton("Red");

	buttonPanel = new JPanel();
	
	buttonPanel.add(yellowButton);
	buttonPanel.add(blueButton);
	buttonPanel.add(redButton);
 
        ColorAction yellowAction = new ColorAction(Color.YELLOW);
	ColorAction blueAction = new ColorAction(Color.BLUE);
        ColorAction redAction = new ColorAction(Color.RED);

        // associate actions with buttons using addActionListener

	yellowButton.addActionListener(yellowAction);
	blueButton.addActionListener(blueAction);
	redButton.addActionListener(redAction);
	
	this.add(buttonPanel);
    }

    /**
       an action listener that sets the panel's background color.
       (note: a PRIVATE INNER CLASS - defined INSIDE another class -
       and it can see the data fields of the class it is within)
    */

    private class ColorAction implements ActionListener
    {
        // data field

	private Color backgroundColor;

	/**
            create an instance of this action listener

            @param col the desired color for the background
	*/

	public ColorAction (Color col)
	{
	    this.backgroundColor = col;
	}

	/**
           set the background color as specified
           
           @param event the button push requesting a background color

	*/

	public void actionPerformed(ActionEvent event)
	{
	    // note that an inner class can SEE the data fields of
	    //    the class it is contained in

	    buttonPanel.setBackground(this.backgroundColor);
	}
    }
}