KeyStroke to remove in Java Swing

I am trying to use InputMap / ActionMap to intercept the delete key. I get it to work with Enter, but it does not respond to deletion (this is on Mac OSX, so I wonder if this is part of the problem).

What am I doing wrong?

private void setupKeyBindings(final JList jlist) {
        String delAction = "deleteItems";
        KeyStroke delKey = KeyStroke.getKeyStroke("DELETE");
        jlist.getInputMap().put(delKey, delAction);
        jlist.getActionMap().put(delAction, new AbstractAction()
        {
            @Override public void actionPerformed(ActionEvent e) {
                System.out.println("delete pressed");
                doDelete(jlist);
            }
        });     

        String enterAction = "useItems";
        KeyStroke enterKey = KeyStroke.getKeyStroke("ENTER");
        jlist.getInputMap().put(enterKey, enterAction);
        jlist.getActionMap().put(enterAction, new AbstractAction()
        {
            @Override public void actionPerformed(ActionEvent e) {
                System.out.println("enter pressed");
            }
        });
    }
+3
source share
3 answers

Hm. The delete key on my Mac seems to map to Keycistener Key Key 8, which I think is backspace. (On the Mac keyboard, as well as on keyboards for a Windows PC, there is only a delete key, not a separate return key)

The following shows how the Mac works to display the Command-Delete command:

KeyStroke delKey = KeyStroke.getKeyStroke(
   KeyEvent.VK_BACK_SPACE, InputEvent.META_MASK);
+7
source
KeyStroke.getKeyStroke("BACK_SPACE");

Worked for me.

+3
source

, :

deleteAction.putValue(
    javax.swing.Action.ACCELERATOR_KEY,
    KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)
);

Integer Integer: https://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html

+1
source

Source: https://habr.com/ru/post/1789630/


All Articles