Java 键触发动作侦听器
我有一个计算器程序,它通过点击一个按钮来工作——将文本附加到一个字符串,然后传递并转换成一个double来进行计算Java 键触发动作侦听器,java,swing,jbutton,actionlistener,Java,Swing,Jbutton,Actionlistener,我有一个计算器程序,它通过点击一个按钮来工作——将文本附加到一个字符串,然后传递并转换成一个double来进行计算 but1.addActionListener(this); if (source==but1) // Number buttons shows the text to display { text.append("1"); } public double number_convert() // Converts the string bac
but1.addActionListener(this);
if (source==but1) // Number buttons shows the text to display
{
text.append("1");
}
public double number_convert() // Converts the string back to double
{
double num1;
String s;
s = text.getText();
num1 = Double.parseDouble(s); // creating a double from the string value.
return num1; //returns value
}
我需要通过键盘键运行按钮的ActionListener
。有什么办法吗
计算器上的所有东西都可以工作,我只需要一种在按下键盘键时运行按钮的方法 最简单的解决方案是结合使用
操作
和键绑定API。有关详细信息,请参阅和
NumberAction action = new NumberAction(1);
JButton btn = new JButton(action);
InputMap im = btn.getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = btn.getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0), "Number1");
am.put("Number1", action);
还有一个通用示例操作
public class NumberAction extends AbstractAction {
private int number;
public NumberAction(int number) {
this.number = number;
putValue(NAME, Integer.toString(number));
}
@Override
public void actionPerformed(ActionEvent e) {
// Deal with the number...
}
}
操作
可用于按钮和键绑定,使它们非常灵活