Use Action class : Swing Action « Event « Java

Use Action class

Use Action class

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");

  private Component target;

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setSize(300, 200);
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {

    JPanel panel = new JPanel();

    Action blueAction = new ColorAction("Blue", new ImageIcon(
        "blue-ball.gif"),, panel);
    Action yellowAction = new ColorAction("Yellow", new ImageIcon(
        "yellow-ball.gif"), Color.yellow, panel);
    Action redAction = new ColorAction("Red",
        new ImageIcon("red-ball.gif"),, 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();

    JMenu m = new JMenu("Color");
    JMenuBar mbar = new JMenuBar();



Related examples in the same category

1.You can change event behavior dynamicallyYou can change event behavior dynamically
2.Keymap and KeyStroke DemoKeymap and KeyStroke Demo
3.How to have multiple listeners
4.Derive a class from a component and implement an action listener inside the class.
5.Demonstrate a listener being reusedDemonstrate a listener being reused