JButton KeyPressed-什么都不会发生 [英] JButton KeyPressed - Nothing Happens

查看:119
本文介绍了JButton KeyPressed-什么都不会发生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使其按右箭头键与按JButton相同.我可以将右箭头键绑定到按钮本身-但这意味着我必须先按一下按钮才能使用右键.现在,我尝试查看是否要绑定到实际的JFrame,但是当我完全绑定到框架时,我什么也没发生:

I'm trying to make it so that pressing the right arrow key does the same thing as pressing a JButton. I can bind the right arrow key to the button itself - but that means I have to have pressed the button before the right key works. Now I'm trying to see if binding to the actual JFrame is what I want, but I can't get anything to happen when I bind to the frame at all:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    onButtonPress();
}                                        

private void formKeyPressed(java.awt.event.KeyEvent evt) {                                
    if (evt.getKeyCode() == KeyEvent.VK_RIGHT){
        onButtonPress();
    }
} 

private void onButtonPress() {
    pressNum++;
    jLabel1.setText("Button has been pressed " + pressNum + " times.");
}

推荐答案

作为一般的经验法则,应避免使用KeyListener.主要原因是,为了使KeyListener生成键事件,其注册到的组件必须是可聚焦的并且具有键盘焦点.在您的情况下,这可能意味着在用户界面的每个组件中添加KeyListener,它们可能"获得键盘焦点,而不是在现实世界中实用的东西.

As a general rule of thumb, you should avoid KeyListener. The main reason is, in order for a KeyListener to generate key events, the component it is registered to must be focusable AND have keyboard focus. In your case, this would probably mean adding a KeyListener to every component in your UI which "might" gain keyboard focus, not something which is practical in the real world.

相反,您应该使用密钥绑定API ,它为您定义了触发相关操作所需的焦点级别.

Instead, you should make use of the Key Bindings API, which provides you the means to define the level of focus required in order for it to trigger the associated actions.

Key Bindings API和示例使用了 s API ,它使我可以定义一个工作单元,该工作单元可以应用于多个可操作的"控件

The Key Bindings API and the example make use of the Actions API, which allows me to define a single unit of work which can be applied to a number of "actionable" controls

该示例还利用了委托/回调/侦听器(即CounterListener),这使我可以将副作用"与动作本身分离.

The example also makes use of a delegate/callback/listener (namely CounterListener) which allows me to decouple the "side effects" from the action itself.

这基本上意味着Action可以执行所需的操作,但是其他"相关方可以在更改时执行其他操作.您可以将ActionListener附加到Action,但这只是实现起来更简单,更快捷

This basically means that the Action can do what it needs to do, but "other" interested parties can perform some other action when it changes. You could, equally attach an ActionListener to the Action, but this was just simpler and quicker to implement

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

public class Test {

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

    public Test() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            JLabel label = new JLabel("...");
            MyAwesomeAction action = new MyAwesomeAction(new CounterListener() {
                @Override
                public void counterChanged(int count) {
                    label.setText("Button has been pressed " + count + " times");
                }
            });

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            JButton button = new JButton(action);
            add(button, gbc);
            add(label, gbc);

            InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
            ActionMap am = getActionMap();

            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "MakeItSo");
            am.put("MakeItSo", action);
        }

    }

    public interface CounterListener {

        public void counterChanged(int count);
    }

    public class MyAwesomeAction extends AbstractAction {

        private int count;
        private CounterListener listener;

        public MyAwesomeAction(CounterListener listener) {
            putValue(NAME, "Make it so");
            this.listener = listener;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            count++;
            listener.counterChanged(count);
        }

    }

}

这篇关于JButton KeyPressed-什么都不会发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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