1

我的代码有这个问题,我正在尝试学习如何在 Java 中使用击键,并且我希望能够跟踪我正在按下的击键。我正在尝试使用 KeyEvent.VK_UP 来跟踪我正在按下的内容。

import java.awt.event.*;
import javax.swing.*;

public class TrackArrows
{
    protected static InputMap inputMap;

    public static void main(String[] arg){
        JPanel panel = new JPanel();

        inputMap = panel.getInputMap();

        panel.getActionMap().put("keys", new AbstractAction() {
            public void actionPerformed(ActionEvent e){
                if(inputMap.get(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), true)){//My problem lies here
                    System.out.println("Key pressed up");
                }
                if(inputMap.get(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), true)){//And here
                    System.out.println("Key pressed down");
                }
            }
        });

        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "keys");
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "keys");

        JFrame frame = new JFrame();
        frame.getContentPane().add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(20,20);
        frame.setVisible(true);
    }
}

我这样做是错的,还是有其他方法可以做到这一点?

4

1 回答 1

4

The Action does not have access to the KeyStroke. You need to create a separate Action for each key binding. Something like this:

class SimpleAction extends AbstractAction
{
    public SimpleAction(String name)
    {
            putValue( Action.NAME, "Action " + name );
    }

    public void actionPerformed(ActionEvent e)
    {
        System.out.println( getValue( Action.NAME ) );
    }
}

Then you create the Actions like:

Action up = new SimpleAction("Up");

However you will still have problems because the default InputMap only receives the key events when it has focus and by default a JPanel is not focusable. So you have two options:

a) make the panel focusable:

panel.setFocusable( true );

b) use a different InputMap:

inputMap = panel.getInputMap(JPanel.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

The Key Bindings article attempts to simplify some of the key bindings concepts from the Swing tutortial.

于 2010-09-16T15:59:50.820 回答