Java_logo_icon
PHP

How to Make a Simple Calculator in Java

Java is a programming language and computing platform first released by Sun Microsystems in 1995. There are lots of applications and websites that will not work unless you have Java installed, and more are created every day. Java is fast, secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere.

import java.awt.*;
import java.awt.event.*;
class CalcForm extends Frame{
	Label fn,sn,rs;
	TextField tfn,tsn,trs;
	Button clear,add;
	CalcForm(String title){
		super(title);//sets title
		setLayout(null);//we can use setBounds() function to place in coordinates
		setSize(350,300);
		addWindowListener(new MyWindowAdapter(this));
		fn=new Label("First Number");
		add(fn);
		fn.setBounds(30,50,100,20);
		
		tfn=new TextField();
		add(tfn);
		tfn.setBounds(150,50,150,20);
		
		sn=new Label("Second Number");
		add(sn);
		sn.setBounds(30,100,100,20);
		
		tsn=new TextField();
		add(tsn);
		tsn.setBounds(150,100,150,20);
		
		clear=new Button("Clear");
		add(clear);
		clear.setBounds(150,150,40,20);
		clear.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				clear_click();
				
			}
		});
		
		add=new Button("Add");
		add(add);
		add.setBounds(200,150,40,20);
		add.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				add_click();
				
			}
		});

		rs=new Label("Result is");
		add(rs);
		rs.setBounds(30,200,80,20);
		
		trs=new TextField();
		add(trs);
		trs.setBounds(150,200,150,20);
		
	
		
		
		
	}
	
	void add_click(){
		int a,b;
		a=Integer.parseInt(tfn.getText());
		b=Integer.parseInt(tsn.getText());
		int s=a+b;
		trs.setText(String.valueOf(s));
	
	}
	
	void clear_click(){
		tfn.setText("");
		tsn.setText("");
		trs.setText("");
	}
}


class MyWindowAdapter extends WindowAdapter{
	CalcForm calc;
	public MyWindowAdapter(CalcForm calc) {
		// TODO Auto-generated constructor stub
		this.calc=calc;
	}
	
	public void windowClosing(WindowEvent e){
		calc.setVisible(false);
		calc.dispose();
	}
}


public class Calculator {
	public static void main(String args[]){
		CalcForm calc=new CalcForm("Calculator");
		calc.setVisible(true);
	}
	
}

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.