简体   繁体   English

Java键绑定无效

[英]Java Key Bindings Not Working

I am trying to make key bindings in Java on a JPanel. 我正在尝试在JPanel上的Java中进行键绑定。 I want a certain action to execute when I press the 'w' button. 我希望在按下“ w”按钮时执行某些操作。 I follow the Java tutorial on making bindings, but the actionPerformed method does not execute (ie no text prints out). 我遵循Java教程进行绑定,但是actionPerformed方法不执行(即,没有打印出文本)。 The following is the entirety of the code for my test GUI, with the relevant part highlighted: 以下是我的测试GUI的全部代码,并突出显示了相关部分:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

@SuppressWarnings("serial")
public class Test extends JFrame{

private JPanel panel;

public Test(){
    super();
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(500,500);
    setLayout(new BorderLayout());
    setVisible(true);        
    panel = new JPanel();

    // HERE ARE THE KEY BINDINGS
    panel.getInputMap().put(KeyStroke.getKeyStroke('w'),"forward");
    panel.getActionMap().put("forward", new AbstractAction(){
        @Override
        public void actionPerformed(ActionEvent e){
            System.out.println("test");
        }
    });
    // END OF KEY BINDINGS

    add(panel, BorderLayout.CENTER);
}

public static void main(String[] args){
    new Test();     
}

}

The text "test" is never printed. 永远不会打印文本“ test”。 I have tried many times with many different variants, different keys, and I make sure the panel is in focus, but no luck. 我已经尝试了很多次,使用了许多不同的变体,不同的键,并且确保面板聚焦,但没有运气。 What am I doing wrong? 我究竟做错了什么?

The problem is the way in which you are looking up the KeyStroke . 问题是您查找KeyStroke KeyStroke.getKeyStroke('w') will return typed w , which for some reason, doesn't trigger a key event. KeyStroke.getKeyStroke('w')将返回typed w ,由于某种原因,它不会触发键事件。 This is why I tend to avoid this method. 这就是为什么我倾向于避免这种方法的原因。 Instead use 改为使用

panel.getInputMap().put(KeyStroke.getKeyStroke("W"),"forward");

or 要么

panel.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0),"forward");

Also, you may want to define the focus constraint for the InputMap , something like 另外,您可能想为InputMap定义焦点约束,类似

panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)...

Would be safer...but you will need to decided at what level you want the key strokes to triggered from 会更安全...但是您将需要确定要从哪个级别触发击键

See JComponent and How to use Key Bindings for more details 有关更多详细信息,请参见JComponent如何使用键绑定

Updated with example 更新了示例

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test extends JFrame {

    private JPanel panel;

    public Test() {
        super();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500, 500);
        setLayout(new BorderLayout());
        setVisible(true);
        panel = new JPanel();

        // HERE ARE THE KEY BINDINGS
        panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "forward");
        panel.getActionMap().put("forward", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("test");
            }
        });
        // END OF KEY BINDINGS

        add(panel, BorderLayout.CENTER);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                new Test();
            }
        });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM