tags:

views:

33

answers:

2
public class XXX 
{
    public static void main(String args[]) {
        JComponent comp = new JTable(); // some panel or table
        comp.getInputMap().put(KeyStroke.getKeyStroke("F4"), "xxxaction");
        comp..getActionMap().put("xxxaction", new XXXAction());
    }

    public class XXXAction extends AbstractAction
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
             // Something;
        }
    }
}

Is there a way to execute the invoked action XXXAction() without pressing 'F4' using the ActionMap lookup??

Many thanks in advance!!!

A: 

I can suggest two possible ways:

  1. Register your action with a Component such as a JButton. That way the Action will be invoked when you manually click the button with the mouse.
  2. Define a method invokeAction() on your class XXX that calls the action, either by retrieving the action from the ActionMap via its key, or by retaining an explicity instance variable reference to it as well as placing it in the ActionMap.
Adamski
A: 

General code would be:

Action action = component.getActionMap().get("...");

if (action != null)
{
    ActionEvent ae = new ActionEvent(component, ActionEvent.ACTION_PERFORMED, "");
    action.actionPerformed( ae );
}

You will need to know if a String value is required for the ActionEvent.

camickr
it worked! thank you so much :)
Santhan
But.. one thing.. what is that 'command string' in ActionEvent(..) mean?? Now, I am giving an empty string and things seem to work. Is that fine to leave it as empty??
Santhan
Generally it will be empty. However some Actions may require a paremeter. For example, I believe the default FontSize Action from the editor kit need a string that can be converted to an integer value (8, 10, 12...) to be used as the font size. If you you are creating a custom Action you can control whether a String value is required or not.
camickr
Oh.. Now I get it.. Thank you!
Santhan