Java密钥绑定不起作用 [英] Java Key Bindings Not Working

查看:151
本文介绍了Java密钥绑定不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在JPanel上使用Java进行密钥绑定。当我按下w按钮时,我想要执行某个动作。我遵循关于进行绑定的Java教程,但是actionPerformed方法没有执行(即没有文本打印出来)。以下是我的测试GUI的全部代码,相关部分突出显示:

I am trying to make key bindings in Java on a JPanel. I want a certain action to execute when I press the 'w' button. I follow the Java tutorial on making bindings, but the actionPerformed method does not execute (i.e. no text prints out). The following is the entirety of the code for my test GUI, with the relevant part highlighted:

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

}

文本test永远不会打印。我已尝试过多次使用许多不同的变体,不同的键,我确保面板是焦点,但没有运气。我究竟做错了什么?

The text "test" is never printed. 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?

推荐答案

问题在于你查找 KeyStroke 。 KeyStroke.getKeyStroke('w')将返回键入w ,由于某种原因,它不会触发键事件。这就是为什么我倾向于避免这种方法。而是使用

The problem is the way in which you are looking up the KeyStroke. KeyStroke.getKeyStroke('w') will return typed w, which for some reason, doesn't trigger a key event. This is why I tend to avoid this method. Instead use

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

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

此外,您可能想要定义 InputMap的焦点约束,类似于

Also, you may want to define the focus constraint for the InputMap, something like

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

请参阅 JComponent 如何使用密钥绑定获取更多详细信息

See JComponent and How to use Key Bindings for more details

已更新为示例

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

这篇关于Java密钥绑定不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆