加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java KeyListener与Keybinding

发布时间:2020-12-15 07:36:55 所属栏目:Java 来源:网络整理
导读:我想写一个计算器并遇到问题.我已经为所有按钮创建了一个actionlistener,现在我希望能够从键盘输入数据.我是否需要为KeyListener或Keybinding完成整个事情,还是有任何其他方法可以在单击按钮后将其发送到actionlistener中的指令?什么更好:Keylistener或Key
我想写一个计算器并遇到问题.我已经为所有按钮创建了一个actionlistener,现在我希望能够从键盘输入数据.我是否需要为KeyListener或Keybinding完成整个事情,还是有任何其他方法可以在单击按钮后将其发送到actionlistener中的指令?什么更好:Keylistener或Keybinding

解决方法

一般来说,如果您有一组有限的键输入,键绑定是更好的选择.

KeyListener遇到与可聚焦性相关的问题以及GUI中的其他控件,焦点将始终远离组件(使用KeyListener).

一个简单的解决方案是使用Actions API.这允许您定义一个自包含的“动作”,它充当ActionListener,但也带有可用于配置其他UI组件的配置信息,特别是按钮

例如…

采用可以表示任意数字的通用NumberAction(现在将其限制为0-9)……

public class NumberAction extends AbstractAction {

    private int number;

    public NumberAction(int number) {
        putValue(NAME,String.valueOf(number));
    }

    public int getNumber() {
        return number;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int value = getNumber();
        // Do something with the number...
    }

}

你可以做点什么……

// Create the action...
NumberAction number1Action = new NumberAction(1);
// Create the button for number 1...
JButton number1Button = new JButton(number1Action);

InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
// Create a key mapping for number 1...
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1,0),"number1");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD1,"number1");

ActionMap am = getActionMap();
// Make the input key to the action...
am.put("number1",number1Action);

而且你已经完成了……

您还可以为相同的数字创建任意数量的NumberAction实例,这意味着您可以单独配置UI和绑定,但是知道在触发时,它们将执行相同的代码逻辑,例如……

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读