Actions.java

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


/**
A short example of Action objects with menus and buttons.
*/
class Actions extends JFrame
{
    public static void main(String argv[])
    {
        Actions f = new Actions();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.show();
    }


    public Actions()
    {
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension ss = kit.getScreenSize();
        setSize(ss.width/3,ss.height/6);
        setLocation(ss.width/4,ss.height/4);
        setTitle("CISC370-011 -- Action objects demo");

        JPanel sp = new JPanel();
        Container contentPane = getContentPane();
        contentPane.add(sp);

        // Create a menu bar and a File menu.
        JMenuBar mbar = new JMenuBar();
        setJMenuBar(mbar);
        JMenu fileMenu = new JMenu("File");
        mbar.add(fileMenu);

        // Create some Action objects...
        ColorAction redAction = 
            new ColorAction(sp,Color.RED,"Red");
        ColorAction yellowAction = 
            new ColorAction(sp,Color.YELLOW,"Yellow");
        ColorAction greenAction = 
            new ColorAction(sp,Color.GREEN,"Green");
        // ...and add the corresponding buttons to the panel...
        JButton redButton = new JButton(redAction);
        JButton yellowButton = new JButton(yellowAction);
        JButton greenButton = new JButton(greenAction);
        sp.add(redButton);
        sp.add(yellowButton);
        sp.add(greenButton);

        // Add the actions to the Colors submenu.
        JMenu optionsMenu = new JMenu("Colors");
        JMenuItem redOption = new JMenuItem(redAction);
        JMenuItem yellowOption = new JMenuItem(yellowAction);
        JMenuItem greenOption = new JMenuItem(greenAction);
        optionsMenu.add(redOption);
        optionsMenu.add(yellowOption);
        optionsMenu.add(greenOption);
        fileMenu.add(optionsMenu);

        // Finally, add an Exit item to the File menu.
        fileMenu.addSeparator();
        JMenuItem exitItem = new JMenuItem("Exit");
        fileMenu.add(exitItem);
        exitItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e)
                    { System.exit(0); }
            });
    }
}


/**
This class represents an <code>Action</code> that, whenever triggered,
sets the background of a given JPanel to a specified color.
*/
class ColorAction extends AbstractAction
{
    public ColorAction(JPanel p,Color c,String name)
    {
        super(name);
        this.color = c;
        this.panel = p;
    }
    public void actionPerformed(ActionEvent e)
    {
        panel.setBackground(color);
    }
    private JPanel panel;
    private Color color;
}