Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 键触发动作侦听器_Java_Swing_Jbutton_Actionlistener - Fatal编程技术网

Java 键触发动作侦听器

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

我有一个计算器程序,它通过点击一个按钮来工作——将文本附加到一个字符串,然后传递并转换成一个double来进行计算

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...
    }
}
操作
可用于按钮和键绑定,使它们非常灵活