Coders Packet

Java Code Expandable Calculator

By Maheen Siraj

The given Java program implements a simple calculator using Java Swing elements. It creates a calculator window

The given program is a Java application that creates a simple calculator using Java Swing elements. The calculator allows basic arithmetic operations such as addition, subtraction, multiplication, and division.

The program starts by creating a JFrame, which serves as the main window for the calculator. It also initializes a JTextField that will display the input and output. The calculator class extends JFrame and implements the ActionListener interface to handle button clicks.

Inside the main function, the program creates various buttons for numbers (0-9), operators (+, -, *, /), and additional functionality (clear and equals). These buttons are created using the JButton class from the Java Swing library. The buttons are then added to a JPanel, which acts as a container to hold the calculator's elements.

The ActionListener is added to each button, so when a button is clicked, the actionPerformed method is invoked. In this method, the program checks which button was clicked by retrieving its label using the getActionCommand() method. Depending on the button clicked, different actions are performed.

If a number or a decimal point is clicked, the program checks whether an operand is already present. If it is, the number is added to the second operand (s2), otherwise, it is added to the first operand (s0). The text field is updated accordingly.

If the "C" button is clicked, the calculator is cleared, and all operands are set to empty strings. The text field is updated to reflect the cleared state.

If the equals (=) button is clicked, the program performs the arithmetic operation based on the stored operator (s1) and the operands (s0 and s2). The result is displayed in the text field, and the first operand (s0) is updated to hold the result.

For the other operator buttons (+, -, *, /), the program checks if there is already an operator and a second operand. If not, the operator is stored in s1. Otherwise, the program performs the previous operation and updates the text field accordingly.

The program uses the try-catch block to set the system's look and feel to ensure the application's appearance matches the underlying operating system.

Finally, the program sets the size of the JFrame, sets the JPanel as its content, and displays the calculator window.

In summary, this Java program demonstrates a basic calculator application built using Java Swing elements. It showcases event handling, button clicks, and performing simple arithmetic operations.

Download Complete Code

Comments

No comments yet

Download Packet

Reviews Report

Submitted by Maheen Siraj (maheenxsiraj)

Download packets of source code on Coders Packet