Calculator Program Using Java AWT and Swing
Then, we create the Calculator class. We will need to handle the button-press events, so the class should implement the ActionListener interface.
Next, we define and initialize several instance variables for the class, including the application frame, result box, control button, number buttons, etc.
We also instantiate the Calculator class from the main method.
Inside the no-arguments constructor for the class, we can set the frame properties, position the various UI elements within the frame, and finally add those elements to the frame.
Then, to react to the button presses, we attach event listeners to each of the elements. Since the Calculator class itself implements the ActionListener interface, we can attach the class itself by using the this keyword.
Next, we need to override the actionPerformed method.
Since the Calculator class is assigned as the action listener for each of the buttons, whenever an action event occurs, the actionPerfomed method is invoked.Inside the actionPerformed method, we find the source of the event, cast it to a JButton instance, and respond accordingly.
For example, if the button was the addBtn button for addition, we initialize the operator instance variable and set it as Operator.PLUS.
If the button was the equalBtn for computing the result, we calculate the result number depending on the value of the operator variable set prior, and display the number on the result box.
With this, the application is complete.
The final program should look like the following.
There you go, we have just built a functional, GUI-based calculator application using Java AWT and Swing.