问题描述
我正在尝试编写一个计算器,但遇到了问题.我已经为所有按钮制作了一个动作监听器,现在我想让从键盘输入数据成为可能.我是否需要为 KeyListener 或 Keybinding 做整个事情,还是有其他方法可以在单击按钮后将其发送到 actionlistener 中的指令?还有什么更好的:Keylistener 或 Keybinding
i am trying to write a calculator and having a problem. I already made a actionlistener for all buttons and now i want to make it possible to input data from keyboard. DO i need to do the whole thing for KeyListener or Keybinding or is there any other a way to make that after clicking a button it will be sent to the instructions in actionlistener? And whats better:Keylistener or Keybinding
推荐答案
一般来说,当您的键输入集有限时,键绑定是更好的选择.
Generally speaking, where you have a limited set of key inputs, key bindings are a better choice.
KeyListener
存在与可聚焦性和 GUI 中的其他控件相关的问题,焦点将始终从组件(使用 KeyListener
)移开.
KeyListener
suffers from issues related to focusability and with other controls in the GUI, focus will constantly be moving away from the component (with the KeyListener
) all the time.
一个简单的解决方案是使用 Action代码>s API
.这允许您定义一个自包含的动作",它充当 ActionListener
,但也携带可用于配置其他 UI 组件的配置信息,特别是按钮
A simple solution would be to use the Action
s API. This allows you to define a self contained "action" which acts as a ActionListener
but also carries configuration information that can be used to configure other UI components, in particular, buttons
例如...
采用可以表示任何数字的通用 NumberAction
(暂时将其限制为 0-9)...
Take a generic NumberAction
which could represent any number (lets limit it to 0-9 for now)...
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, 0), "number1");
ActionMap am = getActionMap();
// Make the input key to the action...
am.put("number1", number1Action);
你已经完成了...
您还可以为相同数量的 NumberAction
创建任意数量的实例,这意味着您可以分别配置 UI 和绑定,但要知道,当触发时,它们将执行相同的代码逻辑,例如...
You can also create any number of instance of the NumberAction
for the same number, meaning you could configure the UI and the bindings separately, but know that when triggered, they will execute the same code logic, for example...
这篇关于Java KeyListener 与键绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!