Re: KeyListener CMD+W

Posted by dscho on
URL: http://imagej.273.s1.nabble.com/KeyListener-CMD-W-tp3690923p3690924.html

Hi Alex,

On Mon, 5 Oct 2009, Alexander Haid wrote:

> I am programming my own plugin in java. I am using a JDialog window to
> display all the buttons, etc.
>
> Now I wanted to add a small, but useful function to my plugin: that the
> user is able to close the plugin dialog with the common key shortcuts -
> under mac osx CMD+w or windows CTRL+w.
>
> Already read the programming example about Key Listeners
> (http://rsbweb.nih.gov/ij/plugins/key-listener.html). But could not figure
> out how to fetch combinded key-strokes like the ones I wannt to act on? Can
> someone tell me how to do that the best way?

This is how we do the things in Fiji:

http://pacific.mpi-cbg.de/cgi-bin/gitweb.cgi?p=fiji.git;a=commitdiff;h=3d1569da99ca90ca6c3d6721f7afec069c9c52c6

In short, we use this method:

-- snip --
       /**
        * Add a keyboard accelerator to a container.
        *
        * This method adds a keystroke to the input map of a container that
        * sends an action event with the given source to the given listener.
        */
        public static void addAccelerator(final Component source,
                       final JComponent container,
                       final ActionListener listener, int key, int modifiers) {
                container.getInputMap(container.WHEN_IN_FOCUSED_WINDOW)
                       .put(KeyStroke.getKeyStroke(key, modifiers), source);
                if (container.getActionMap().get(source) != null)
                        return;
                container.getActionMap().put(source,
                                new AbstractAction() {
                        public void actionPerformed(ActionEvent e) {
                                if (!source.isEnabled())
                                        return;
                                ActionEvent event = new ActionEvent(source,
                                        0, "Accelerator");
                                listener.actionPerformed(event);
                        }
                });
        }
-- snap --

and we use it like this (just after the call to pack(), but you can place
it anywhere, really):

-- snip --
                       addAccelerator(cancel, (JComponent)contentPane, this,
                               KeyEvent.VK_W, Toolkit.getDefaultToolkit()
                                       .getMenuShortcutKeyMask());
-- snap --

As you probably guessed, the "cancel" variable refers to a JButton doing
the job, but it really can be any component that the ActionListener knows
should trigger the "cancel".

Feel free to use the code as you see fit (i.e. this is my code and I
explicitely give up GPLv2 on it, just in case anybody thinks this is
untrivial enough to enforce a license or some such).

Ciao,
Dscho