I'm writing a simple calculator program using jFrame. I would like to press the numbers by my keyboard instead of clicking on it by my mouse... How could I do this ? My Simple Calculator
Asked
Active
Viewed 1,906 times
-1
-
Why not create a method that listens for a click/keyboard press and inputs the value on the calculator screen? I mean you can handle keyboard events just the way you handle the click events too. – Chuks Apr 19 '18 at 21:45
-
Probably the best solution is going to be using the [Key Bindings API](https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) to detect the key press and then trigger the button through the `doClick` method, which will "act" like the button was pressed by the user – MadProgrammer Apr 19 '18 at 22:04
2 Answers
0
You just have to change a property to JButton, to get a short path
Exmple :
buttonOne.setMnemonic(KeyEvent.VK_C);

Abdo Bmz
- 632
- 1
- 11
- 24
-1
Just add the key listener to your class and inherit its method what you must use from keylistener method is the keypressed method just copy my code and the other numbers and write your code when he pres one of them key is your data type (in case you didn't know).
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_1) {
//write the code here when he presses 1
}
if (key == KeyEvent.VK_2) {
//write the code here when he presses 2
}
if (key == KeyEvent.VK_3) {
//write the code here when he presses 1
}
if (key == KeyEvent.VK_4) {
//write the code here when he presses 1
}
}

Positive Navid
- 2,481
- 2
- 27
- 41

Sideeg MoHammed
- 375
- 2
- 10
-
Thanks for your answer. @Samuel Neche and I tried to improve your answer, but it's very difficult to understand, even for editors. Please use proper punctuation to improve your answer. Thanks again. – Positive Navid Nov 20 '22 at 07:00