-1

I am working on a calculator project on computer with jdk8 library. My goal is to get a working calculator from its interaction with the user through the computer keyboard. For this I was advised to use the keyPressed method from the standard library of the java in order to be able to use the keyboard keys for the operation of my software. I have successfully implemented the keypressed method. Then, I wrote a code so that when I press a key on the computer keyboard, for example b, that it activates a key on the keyboard of said calculator which will in turn display on the screen the calculator, the number it carries for example 2.

But problem, whenever I press the b key, it always returns 2b on my calculator screen.

Here is my code so that the b key on the computer can return the number 2 on my calculator screen with "screen" the name of my JTextField and "buttonTwo" the name of my Jbutton for key 2:

public void keyPressed ( KeyEvent e ) {

super.keyPressed(e) ;

int key = e.getKeyCode() ;

if ( key == KeyEvent.VK_B ) {

String buttonTwoText = Screen.getText() + buttonTwo.getText() ;

Screen.setText(buttonTwoText);

}

}

And this is what the debugger displays: enter image description here

  • 1
    If you want it to display "2", why don't you just have `Screen.setText("2");`? The reason it's displaying "2b" is because `Screen.getText()` returns "2" and `buttonTwo.getText()` returns "b"`, so when you put those together it displays "2b". – Roddy of the Frozen Peas Aug 17 '21 at 21:59
  • You don't implement keyPressed. You should NOT use a KeyListener. Instead you should use `Key Bindings`. See: https://stackoverflow.com/questions/33739623/how-to-add-a-shortcut-key-for-a-jbutton-in-java/33739732#33739732 for a basic example. – camickr Aug 17 '21 at 23:17

1 Answers1

1

There is no reason to use a key pressed event when using JTextField, because the event is already perceived by the component. You are not very clear here.

Next time publish all relevant code snippets, not just a small part of the code.

But, I guess what you want to do is to disable editing in the text field, so you can get better control over the text inserted by the user into the calculator display using the keyPressed() method.

Second, you don't need one of them:

Screen.getText()

or

buttonTwo.getText()

Make sure you are actually disabling the editing of the text field and insure that the keyPressed() logic is right (in the if section).

public void keyPressed(KeyEvent e) {
    int key = e.getKeyCode();
    
    if (key == KeyEvent.VK_B)
        yourButton.setText(Screen.getText() + 2);
}
InSaNiTy
  • 150
  • 1
  • 9