Sniplet of AbstractActionDemo.java
/*
This class shows how to extend AbstractAction to create one to one component <-> action mappings.
This way we dont have those huge switch statements in the ActionListener
AbstractAction gives you some extra "stuff" over just making a class which implements ActionListener
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
class Images {
public static final String PATH =
"http://java.sun.com/developer/techDocs/hi/repository/graphicsRepository/toolbarButtonGraphics/general/";
}
class CutAction extends AbstractAction {
public CutAction() {
super("Cut");
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("control X"));
putValue(MNEMONIC_KEY, KeyEvent.VK_C);
putValue(SHORT_DESCRIPTION, "this is the tool tip text for cut");
try {
putValue(SMALL_ICON, new ImageIcon(new URL(Images.PATH + "Cut16.gif")));
putValue(LARGE_ICON_KEY, new ImageIcon(new URL(Images.PATH + "Cut24.gif")));
} catch (IOException e) {
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent evt) {
System.out.println("do cut");
}
}
class CopyAction extends AbstractAction {
public CopyAction() {
super("Copy");
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("control C"));
putValue(MNEMONIC_KEY, KeyEvent.VK_O);
putValue(SHORT_DESCRIPTION, "this is the tool tip text for copy");
try {
putValue(SMALL_ICON, new ImageIcon(new URL(Images.PATH + "Copy16.gif")));
putValue(LARGE_ICON_KEY, new ImageIcon(new URL(Images.PATH + "Copy24.gif")));
} catch (IOException e) {
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent evt) {
System.out.println("do copy");
}
}
public class ActionExample implements Runnable {
public void run() {
Action cut = new CutAction();
Action copy = new CopyAction();
JMenuBar mb = new JMenuBar();
JMenu edit = new JMenu("Edit");
edit.add(cut);
edit.add(copy);
mb.add(edit);
JToolBar tb = new JToolBar();
tb.add(cut);
tb.add(copy);
JFrame f = new JFrame("ActionExample");
f.setJMenuBar(mb);
f.getContentPane().add(tb, BorderLayout.NORTH);
f.getContentPane().add(new JScrollPane(new JTextArea(20,60)));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new ActionExample());
}
}