有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java通过inputmap跟踪击键

我的代码有这个问题,我正在尝试学习如何在Java中使用击键,我希望能够跟踪我按下的击键。我正在尝试使用KeyEvent。VK_跟踪我的压力

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

我这样做是错了,还是有别的方法


共 (1) 个答案

  1. # 1 楼答案

    该操作无法访问按键。您需要为每个键绑定创建单独的操作。比如:

    class SimpleAction extends AbstractAction
    {
        public SimpleAction(String name)
        {
                putValue( Action.NAME, "Action " + name );
        }
    
        public void actionPerformed(ActionEvent e)
        {
            System.out.println( getValue( Action.NAME ) );
        }
    }
    

    然后创建如下操作:

    Action up = new SimpleAction("Up");
    

    但是,您仍然会遇到问题,因为默认的InputMap只有在有焦点时才会接收关键事件,而默认情况下JPanel不可聚焦。所以你有两个选择:

    a)使面板聚焦:

    panel.setFocusable( true );
    

    b)使用不同的输入映射:

    inputMap = panel.getInputMap(JPanel.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    

    本文试图简化Swing Tutorial中的一些关键绑定概念