ColorAction.java Source code

Java tutorial

Introduction

Here is the source code for ColorAction.java

Source

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

public class ColorAction extends AbstractAction {
    public ColorAction(String name, Icon icon, Color c, Component comp) {
        putValue(Action.NAME, name);
        putValue(Action.SMALL_ICON, icon);
        putValue("Color", c);
        target = comp;
    }

    public void actionPerformed(ActionEvent evt) {
        Color c = (Color) getValue("Color");
        target.setBackground(c);
        target.repaint();
    }

    private Component target;

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setTitle("SeparateGUITest");
        frame.setSize(300, 200);
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        JPanel panel = new JPanel();

        Action blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.blue, panel);
        Action yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"), Color.yellow, panel);
        Action redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.red, panel);

        panel.add(new JButton(yellowAction));
        panel.add(new JButton(blueAction));
        panel.add(new JButton(redAction));

        panel.registerKeyboardAction(yellowAction, KeyStroke.getKeyStroke(KeyEvent.VK_Y, 0),
                JComponent.WHEN_IN_FOCUSED_WINDOW);
        panel.registerKeyboardAction(blueAction, KeyStroke.getKeyStroke(KeyEvent.VK_B, 0),
                JComponent.WHEN_IN_FOCUSED_WINDOW);
        panel.registerKeyboardAction(redAction, KeyStroke.getKeyStroke(KeyEvent.VK_R, 0),
                JComponent.WHEN_IN_FOCUSED_WINDOW);

        Container contentPane = frame.getContentPane();
        contentPane.add(panel);

        JMenu m = new JMenu("Color");
        m.add(yellowAction);
        m.add(blueAction);
        m.add(redAction);
        JMenuBar mbar = new JMenuBar();
        mbar.add(m);
        frame.setJMenuBar(mbar);

        frame.show();
    }

}