开发者

KeyStroke for delete in Java Swing

I'm trying to use InputMap/ActionMap to intercept the delete key. I get it to work with Enter but it doesn't seem to respond with delete (this is on a Mac OSX so I wonder if that is part of the issue).

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");
            }
        });
    }


Hmm. The "delete" key on my Mac seems to map to KeyListener keycode 8 which I think is backspace. (There's just a delete key, not a separate backspace key, on my Mac keyboard, vs. Windows PC keyboards that have both)

The following appears to works for the Mac to map to Command-Delete:

KeyStroke delKey = KeyStroke.getKeyStroke(
   KeyEvent.VK_BACK_SPACE, InputEvent.META_MASK);


KeyStroke.getKeyStroke("BACK_SPACE");

Worked for me.


This doesn't directly answer your question, but this answered mine:

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

You can find other KeyEvent integer constants here: https://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜