Java Action attribute

Introduction

Constant Description
NAME Action name, used as button label
SMALL_ICONIcon for the Action, used as button label
SHORT_DESCRIPTION Short description of the Action; could be used as tooltip text, but not by default
LONG_DESCRIPTION Long description of the Action; could be used for accessibility
ACCELERATOR KeyStroke string; can be used as the accelerator for the Action
ACTION_COMMAND_KEY InputMap key; maps to the Action in the ActionMap of the associated JComponent
MNEMONIC_KEYKey code; can be used as mnemonic for action
DEFAULT Unused constant that could be used for your own property


import java.awt.BorderLayout;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.KeyStroke;

public class Main {
   public static void main(String[] argv) throws Exception {

      Action action = new My();
      JButton button = new JButton(action);

      JFrame f = new JFrame();

      f.add(button, BorderLayout.NORTH);
      f.setSize(300, 300);//from w  ww.  j a v  a  2  s  .co m
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setVisible(true);

   }
}

class My extends AbstractAction {
   public My() {
      super("Action Name");
      putValue(Action.SHORT_DESCRIPTION, "Tool Tip Text");
      putValue(Action.LONG_DESCRIPTION, "Help Text");

      Icon icon = new ImageIcon("icon.png");
      putValue(Action.SMALL_ICON, icon);

      putValue(Action.MNEMONIC_KEY, new Integer(java.awt.event.KeyEvent.VK_A));
      putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control F2"));
   }

   public void actionPerformed(ActionEvent evt) {
      System.out.println("action");
   }
};



PreviousNext

Related