Class KeyboardEvents

java.lang.Object
com.project.calculator.KeyboardEvents
All Implemented Interfaces:
KeyListener, EventListener

public class KeyboardEvents extends Object implements KeyListener
The KeyboardEvents class handles keyboard input events for the calculator.

It listens for key presses and performs the appropriate actions, such as:

  • Appending digits and operators to the display.
  • Handling special keys (Enter, Backspace, Delete, and Escape).
  • Supporting both standard and numpad keys.
  • Displaying and calculating the result.

This class interacts with both BaseUI and MainUI instances to update the display and process the input.

  • Field Details

    • baseUiInstance

      private final BaseUI baseUiInstance
      Reference to the BaseUI instance for accessing display and history labels.
    • mainUiInstance

      private final MainUI mainUiInstance
      Reference to the MainUI instance for handling input operations.
  • Constructor Details

    • KeyboardEvents

      KeyboardEvents(BaseUI baseUiInstance, MainUI mainUiInstance)
      Constructs the KeyboardEvents object with references to the UI instances.
      Parameters:
      baseUiInstance - The BaseUI instance for managing the display and history.
      mainUiInstance - The MainUI instance for managing the input operations.
  • Method Details

    • keyTyped

      public void keyTyped(KeyEvent e)
      Handles the key-typed event.

      This method is not used in the current implementation.

      Specified by:
      keyTyped in interface KeyListener
      Parameters:
      e - The KeyEvent triggered by typing a key.
    • keyPressed

      public void keyPressed(KeyEvent e)
      Handles the key-pressed event and performs the corresponding action.

      This method processes the following:

      • Digits, decimal points, and operators.
      • Special keys (Enter, Backspace, Delete, and Escape).
      • Handles both standard and numpad keys.
      Specified by:
      keyPressed in interface KeyListener
      Parameters:
      e - The KeyEvent triggered by pressing a key.
    • keyReleased

      public void keyReleased(KeyEvent e)
      Handles the key-released event.

      This method is not used in the current implementation.

      Specified by:
      keyReleased in interface KeyListener
      Parameters:
      e - The KeyEvent triggered by releasing a key.
    • handleResult

      private void handleResult()
      Handles the evaluation of the expression and displays the result.

      This method:

      • Sets the history label with the current display content.
      • Converts the infix expression to postfix using InfixToPostfix class.
      • Displays the evaluated result.
      • Clears the input and updates it with the result.