Creating a simple calculator using Java AWT

In this Java tutorial, we will learn about the Java AWT(Abstract Window Toolkit). As a result, using this concept we will learn how to build a simple calculator using Java AWT. This calculator has some very simple features of add, subtract, multiply and divide. So let’s get started to learn how to create a simple calculator in Java AWT.

Java AWT(Abstract Window Toolkit)  is an API that helps in building GUI based java applications.GUI helps in user interactions using some graphics. As a result, our operating systems have some underlying GUI’s such as windows, frames,  textfield, labels, etc.

Program to create a simple calculator using Java AWT

import java.awt.*;
import java.awt.event.*;
 
class Calculator implements ActionListener
{
  
Frame f=new Frame();
Label l1=new Label("Enter Number");
Label l2=new Label("Enter Number");
Label l3=new Label("Result");
TextField t1=new TextField();
TextField t2=new TextField();
TextField t3=new TextField();
Button b1=new Button("Add");
Button b2=new Button("Sub");
Button b3=new Button("Mul");
Button b4=new Button("Div");
  
  
Calculator()
{
l1.setBounds(50,100,100,20);
l2.setBounds(50,150,100,20);
l3.setBounds(50,200,100,20);    
t1.setBounds(200,100,100,20);
t2.setBounds(200,150,100,20);
t3.setBounds(200,200,100,20);  
b1.setBounds(50,250,50,20);
b2.setBounds(110,250,50,20);
b3.setBounds(170,250,50,20);
b4.setBounds(230,250,50,20);
f.add(l1);
f.add(l2);
f.add(l3);
f.add(t1);
f.add(t2);
f.add(t3);
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
f.setLayout(null);
f.setVisible(true);
f.setSize(500,500);
}
  
  
public void actionPerformed(ActionEvent e)
{
int i=Integer.parseInt(t1.getText());
int j=Integer.parseInt(t2.getText());
    
if(e.getSource()==b1)
{
t3.setText(String.valueOf(i+j));
}
      
if(e.getSource()==b2)
{
t3.setText(String.valueOf(i-j));
}
    
if(e.getSource()==b3)
{
t3.setText(String.valueOf(i*j));
}
    
if(e.getSource()==b4)
{
t3.setText(String.valueOf(i/j));
}
}
  
public static void main(String args[])
{
new Calculator()
}

In this above program, we saw the implementation of the ActionListener class in our Calculator class where we created a frame, labels, text fields, and some buttons. In its constructor class, we call the setBounds() function to set the location of the text fields and labels and buttons. Consequently, we add all of these to the frame and set the size of the frame using setSize() function. In the actionPerformed function, we take two numbers as input. As a result, we then see whether we want to add, subtract, multiply or divide accordingly the result is displayed.

Also read some other useful tutorials,

Leave a Reply

Your email address will not be published. Required fields are marked *