FileDocCategorySizeDatePackage
Calculator.javaAPI DocExample2387Mon Oct 30 16:14:38 GMT 2000None

Calculator.java

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

public class  Calculator extends Applet implements ActionListener
{
	int currentValue = 0;
	int operand1     = 0;
	int operand2     = 0;
	int result;				// used to hold the calculated result
	int operation;       // 1 = add, 2 = subtract etc
	TextField calculatorDisplay = new TextField(" Calculator     ", 8);
	Panel numPanel = new Panel();
	Panel opsPanel = new Panel();
	Button one   = new Button("1");
								// declare and initialise new digit buttons here
	Button plus  = new Button("+");
								// declare and initialise new operation buttons here
	Button equals = new Button("=");

	public void init()
	{
		numPanel.setLayout(new GridLayout(4,3,5,5));
		add(calculatorDisplay);
		numPanel.add(one);
								// add new digit buttons to numPanel here		
		opsPanel.setLayout(new GridLayout(2,4, 5, 5));		
		opsPanel.add(plus);
								// add new operation buttons to opsPanel here
		opsPanel.add(equals);
		add(numPanel);
		add(opsPanel);
		
		one.addActionListener(this);
								// add actionListeners for digit buttons here
		plus.addActionListener(this);
								// add actionListeners for operation buttons here
		equals.addActionListener(this);
	
		currentValue = 0;		// set currentValue to 0 before we use it
	}
	
    public void actionPerformed(ActionEvent e)
   {
			if(e.getSource() == one)
			{
				currentValue = currentValue * 10 + 1;
				calculatorDisplay.setText(Integer.toString(currentValue));
			}
							// add code for digit button events here
			else if (e.getSource() == plus)
			{
				operand1     = currentValue;
				currentValue = 0;
				calculatorDisplay.setText("0");
				operation    = 1;
			}
									// add code for operation button events here
			else if (e.getSource() == equals)
			{
				operand2     = currentValue;
				currentValue = 0;
				switch (operation)
				{
					case 1: result = operand1  +  operand2; break;
					case 2: result = operand1  -  operand2; break;
					case 3: result = operand1  *  operand2; break;
					case 4: result = operand1  /  operand2; break;
				}
				calculatorDisplay.setText(Integer.toString(result));
				operand1 = operand2 = 0;
			
			}				
			
	}
		
	public void paint(Graphics g)
	{
		setForeground(Color.blue);
		setBackground(Color.yellow);
	}
}