user4436423
user4436423

Reputation:

Key Trigger action listener

I have a calculator program that works by clicking a button - appending the text to a string and later is passed and converted into a double to do the calc.

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 
    }

I need to run the ActionListener for the button by keyboard key. Any ideas how to do this?

Everything works on the calculator I just need a way to run the buttons when a keyboard key is pressed.

Upvotes: 0

Views: 335

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

The simplest solution would be to use a combination of Actions and Key Bindings API. See How to Use Actions and How to Use Key Bindings for more details

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

And a general example 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...
    }
}

The Action can be used for both the button AND the key binding, making them quite flexible...

Upvotes: 2

Related Questions