Advertisements
Home > Java > Java Program to write an Applet having data entry operation (basic calculator) – Q53

Java Program to write an Applet having data entry operation (basic calculator) – Q53


Q53: Java Program to write an applet which have three text fields, first two accepts input from user and third one shows the result. It should have four buttons indicating operation add, subtract, multiply and divide, pressing the button should put the result in the third text field.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.awt.TextField.*;

public class Ap_Calc extends Applet implements ActionListener{
	TextField one, two, res;
	Button add, sub, mul, div;

	public void init(){
		Label l1 = new Label("First Number:   ",Label.RIGHT);
		Label l2 = new Label("Second Number:  ",Label.RIGHT);
		Label l3 = new Label("Result:         ",Label.RIGHT);
 
		one = new TextField(5);
		two = new TextField(5);
		res = new TextField(7);

		add = new Button("Add");
		sub = new Button("Substract");
		mul = new Button("Multiply");
		div = new Button("Divide");

		add(l1);
		add(one);
		add(l2);
		add(two);
		add(l3);
		add(res);
	
		add(add);
		add(sub);
		add(div);
		add(mul);

		one.addActionListener(this);
		two.addActionListener(this);
		res.addActionListener(this);
		add.addActionListener(this);
		sub.addActionListener(this);
		div.addActionListener(this);
		mul.addActionListener(this);		
	}

	public void actionPerformed(ActionEvent ae){
		String str = ae.getActionCommand();
		float b1, b2, b3 = 0;
		String msg;
		
		b1 = Float.parseFloat(one.getText());
		b2 = Float.parseFloat(two.getText());
		
		if(str.equals("Add"))
			b3 = b1 + b2;
		if(str.equals("Substract"))
			b3 = b1 - b2;
		if(str.equals("Divide"))
			b3 = b1 / b2;
		if(str.equals("Multiply"))
			b3 = b1 * b2;
		msg = String.valueOf(b3);
		res.setText(msg);	
		repaint();
	}
	
	public void paint(Graphics g){
	}
}

… from College notes (BCA/MCA assignments):


Advertisements
Categories: Java Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: