Clay (V6): Incorporating Events
CS2 Course Summary Slide 7

Version 6 of the Clay Shell program is like Version 5 except that the buttons are alive! Quite a bit of lecture time was devoted to describing the event generating/handling model in Java.


Demo

java -jar ".../Clay6.jar" -w 400 -h 200

Code

package clay6;

import java.awt.*;
import java.awt.event.*;

public class Main {
    
   <<<Just like in the previous version!>>>

}

class ClayFrame extends Frame  implements ActionListener {
    
    public ClayFrame(String title, Color color, Dimension size) {
        super(title);
        establishColors();
        setBackground(color);
        setSize(size.width,size.height);
        addComponents();
        setVisible(true);
        addWindowListener(new CloseWindow());
    }
    
    private Color backgroundColor;
    private Color hilightColor;
    private Color lolightColor;

    private Button nb;
    private Button sb;
    private Button eb;
    private Button wb;
    private Button cb;
    private Button theButton;  // selection

    private void establishColors()
    {
        Color purplerose = new Color(210,180,200);
        hilightColor = purplerose;
        lolightColor = Color.white;
    }

    private void addComponents()
    {
        // establish the layout manager
        setLayout(new BorderLayout());
        // create five buttons
        nb = new Button("North");
        sb = new Button("South");
        eb = new Button("East");
        wb = new Button("West");
        cb = new Button("Center");
        // set backgrounds of buttons to white
        nb.setBackground(lolightColor);
        sb.setBackground(lolightColor);
        eb.setBackground(lolightColor);
        wb.setBackground(lolightColor);
        cb.setBackground(lolightColor);
        // add action listeners
        nb.addActionListener(this);
        sb.addActionListener(this);
        eb.addActionListener(this);
        wb.addActionListener(this);
        cb.addActionListener(this);
        // add the buttons to the frame
        add(nb,BorderLayout.NORTH);
        add(sb,BorderLayout.SOUTH);
        add(cb,BorderLayout.CENTER);
        add(eb,BorderLayout.EAST);
        add(wb,BorderLayout.WEST);
    }
    
    public void actionPerformed(ActionEvent event)
    {
        Object source = event.getSource();
        if ( source instanceof Button ) {
            theButton = (Button)source;
            // color the buttons
            nb.setBackground(lolightColor);
            sb.setBackground(lolightColor);
            wb.setBackground(lolightColor);
            eb.setBackground(lolightColor);
            cb.setBackground(lolightColor);
            theButton.setBackground(hilightColor);
        }
    }

    class CloseWindow extends WindowAdapter {

       <<<Just like in the previous version!>>>

    }

}