gpt4 book ai didi

Java Swing : KeyBinding for KEY_TYPED event

转载 作者:行者123 更新时间:2023-12-02 03:26:58 25 4
gpt4 key购买 nike

我一直在尝试通过重写书中的问题来学习按键绑定(bind),这些问题是我之前使用 KeyListener 解决的。我正在努力使用按键绑定(bind)解决的问题需要我记录已输入的消息并将其显示在面板上。

使用 KeyListener 解决这个问题的方法很简单,就是使用 keyTyped() 方法记录带有 unicode 的字符,并使用 keyPressed 读取修饰符/非 Unicode 键。如果 KeyEvent.VK_ENTER 与键事件中的键码匹配,则会在面板上显示该字符串。

~~~~~~~~~

我认为可以用KeyBinds类似的方式解决。它在 KeyEvent 文档中说,每次输入字符时都会触发 KeyEvent.KEY_TYPED。我认为这意味着每个具有相应 Unicode 的字符都可以像在 KeyListener 中一样输入。

后来,我意识到我不知道如何检索该字符,因为 Oracle 关于 KeyBinds 的教程说,调用 actionPerformed() 时会消耗 KeyEvent。

这是我认为可以使用 KeyBindings 将键入的键记录到 StringBuilder 的代码:

getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.KEY_TYPED, 0), "recordTypedKey");
getActionMap().put("recordTypedKey", addCharToString);

除了为每个字符添加一个键并使用单独的 Action 事件来记录它们之外,是否还有一种方法可以获得调用 KeyListener 的 keyTyped() 方法的字符?

最佳答案

Is there a way to obtain the characters that would invoke KeyListener's keyTyped() method besides adding a key to every one of them and using a separate Action event to record them?

我不相信有一个全局的KeyStroke可以传递给InputMap,它的工作方式与KeyListener类似,因为KeyBindings在单个键的基础上工作。不过,您可以创建单个 Action 并通过循环处理您希望处理的 char 值来将键绑定(bind)到它 - 在 ActionListener 实现中,您可以通过 getActionCommand 获取键的值。例如处理a-z:

AbstractAction action = new AbstractAction(){

@Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}

};
//loop over the ascii char values
for ( char a = 'A'; a <= 'Z'; a++ ){
panel.getInputMap().put(KeyStroke.getKeyStroke(Character.toString(a)), "recordTypedKey");
}
panel.getActionMap().put("recordTypedKey", action);

如果需要,您可以添加修饰符...例如处理 Shift 键(例如大写),

panel.getInputMap().put(KeyStroke.getKeyStroke("shift " + Character.toString(a)), "recordTypedKey");

关于Java Swing : KeyBinding for KEY_TYPED event,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38706950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com