键触发器动作侦听器

时间:2015-01-09 10:24:01

标签: java swing jbutton actionlistener

我有一个计算器程序,通过单击按钮工作 - 将文本附加到字符串,然后传递并转换为双重来执行计算。

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。任何想法如何做到这一点?

一切都在计算器上工作我只需要在按下键盘键时运行按钮。

1 个答案:

答案 0 :(得分:2)

最简单的解决方案是使用Action和Key Bindings API的组合。有关详细信息,请参阅How to Use ActionsHow to Use Key Bindings

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);

一般例子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...
    }
}

Action可以用于按钮和键绑定,使它们非常灵活......