Web Analytics
Calculator Program Using Java AWT and Swing -->

Calculator Program Using Java AWT and Swing

Learn how to build a simple GUI calculator application using Java AWT and Swing.

In this piece, let's build a simple GUI calculator application using Java AWT and Swing.

Java AWT is a toolkit that helps us build a GUI for a Java program. Swing provides a more sophisticated set of components, and can be seen as an upgrade to AWT.

The application we are building will support addition, subtraction, multiplication, and division operations. It will provide the user with ten digits -- 0 through 9 -- to perform the operations on.

Additionally, the user can clear the display box with a Clear button provided.

GUI of Calculator program

Now lets begin coding!

First, we import the necessary packages for AWT, Swing, and AWT's event handling mechanism.
Then, we enumerate the available operators.

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.



You may like these posts

  1. To insert a code use <i rel="pre">code_here</i>
  2. To insert a quote use <b rel="quote">your_qoute</b>
  3. To insert a picture use <i rel="image">url_image_here</i>