UNB/ CS/ David Bremner/ teaching/ java/ ButtonTest.java
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ButtonTest
{  public static void main(String[] args)
   {  ButtonFrame frame = new ButtonFrame();
      frame.setTitle("ButtonTest");
      frame.show();
   }
}

class ButtonFrame extends JFrame
{  public ButtonFrame()
   {  final int DEFAULT_FRAME_WIDTH = 300;
      final int DEFAULT_FRAME_HEIGHT = 300;
      setSize(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT);

      addWindowListener(new WindowCloser());
      
      // construct components
   
      panel = new RectanglePanel();
      JPanel buttonPanel = new JPanel();

      ActionListener listener = new DirectionListener();

      upButton = new JButton("Up");
      upButton.addActionListener(listener);

      downButton = new JButton("Down");
      downButton.addActionListener(listener);

      leftButton = new JButton("Left");
      leftButton.addActionListener(listener);

      rightButton = new JButton("Right");
      rightButton.addActionListener(listener);

      // add components to content pane
      
      Container contentPane = getContentPane();
      contentPane.add(panel, "Center");

      buttonPanel.add(upButton);
      buttonPanel.add(downButton);
      buttonPanel.add(leftButton);
      buttonPanel.add(rightButton);

      contentPane.add(buttonPanel, "South");
   }
   
   private RectanglePanel panel;
   private JButton upButton;
   private JButton downButton;
   private JButton leftButton;
   private JButton rightButton;
   
   // inner class definition

   private class DirectionListener implements ActionListener
   {  public void actionPerformed(ActionEvent event)
      {  // find the button that was clicked
      
         Object source = event.getSource();
         
         if (source == upButton) 
            panel.moveRectangle(0, -1);
         else if (source == downButton) 
            panel.moveRectangle(0, 1);
         else if (source == leftButton) 
            panel.moveRectangle(-1, 0);
         else if (source == rightButton) 
            panel.moveRectangle(1, 0);
      }
   }

   private class WindowCloser extends WindowAdapter
   {  public void windowClosing(WindowEvent event)
      {  System.exit(0);
      }
   }
}