Search code examples
javanetbeanscalculatorkeypress

How to handle keypresses for a calculator made in Java?


I've made a simple calculator using an tutorial online using Netbeans and it works fine when clicking the respective buttons, however I'm looking to improve it by allowing keypresses to work.

What I'd like is for the numbers 0-9 to work, +, -, *, / and enter as =.

I think I know how to do it, but can't seem to figure it out.

For example, the code for my 1 button is:

private void btnOneActionPerformed(java.awt.event.ActionEvent evt) {                                       
    String btnOneText = txtDisplay.getText() + btnOne.getText();
    txtDisplay.setText(btnOneText);
}  

So for the keypress I created a keypress event but I'm not sure what the code is. I assume it's something like this:

private void jPanel1KeyPressed(java.awt.event.KeyEvent evt) {                                   
    //if statement to check if 1 key has been pressed, then execute rest of code
    String btnOneText = txtDisplay.getText() + btnOne.getText();
    txtDisplay.setText(btnOneText);
} 

However I'm probably completely wrong. Any help?


Solution

  • You can use either of KeyListener or KeyBindings depending on your usage.

    Since you are designing a simple calculator, there is no harm with KeyListener since there are not many controls.

    Demo code for the same is.

    public void keyPressed(KeyEvent e) {
    
    int keyCode = e.getKeyCode();
          switch( keyCode ) {
    
       case KeyEvent.VK_0:
           //handle 0 press
           break;
       case KeyEvent.VK_1:
           // handle 1 press
           break;
       case KeyEvent.VK_2:
           // handle 2 press
           break;
       case KeyEvent.VK_3 :
           // handle 3 press
           break;
       //
     }
    }
    

    You can find the keycodes here : http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html