[Main]

Sum Two Numbers

The following applet will offer the user to enter two numbers.  The sum of the two numbers is performed when the user presses the button.

  Source Code for Applet
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class MSumNumber extends Applet implements ActionListener
    {
        ////////////////
    Panel mPanelX=new Panel();
    Label lblX=new Label("Enter X:");
    TextField txtX = new TextField();

        ////////////////
    Panel mPanelY=new Panel();
    Label lblY=new Label("Enter Y:");
    TextField txtY = new TextField();

        ///////////////
    Panel mInput=new Panel();

        //////////////
    Panel mPanelAns = new Panel();
    Label lblAns=new Label("Ans=");
    Button cmdAns=new Button("Find Sum");

        // Handle only Ans
    public void actionPerformed(ActionEvent ev)
        {
        try   
            {
            Float f1=new Float(txtX.getText()); // May throw an exception
            Float f2=new Float(txtY.getText()); // May throw an exception
           
            float sum; sum = f1.floatValue() + f2.floatValue();
           
            lblAns.setText("Ans=" + sum);
            }
        catch(NumberFormatException ex)
            { lblAns.setText("Error: Number Format");    }
       
        }

    //////////////////////////////////
    public void init()
        {
        mPanelX.setLayout(new GridLayout(1,2)); // Grid Layout(1x2)
        mPanelX.add(lblX); mPanelX.add(txtX); // Add components

        mPanelY.setLayout(new GridLayout(1,2)); // Grid Layout (1x2)
        mPanelY.add(lblY); mPanelY.add(txtY);

        mInput.setLayout(new GridLayout(2,1));
        mInput.add(mPanelX); mInput.add(mPanelY);

        mPanelAns.setLayout(new GridLayout(1,2));
        mPanelAns.add(lblAns); mPanelAns.add(cmdAns);

        this.setLayout(new BorderLayout());
        this.add(mInput,"Center");
        this.add(mPanelAns,"South");

        cmdAns.addActionListener(this); // Handle Events
        }

    public void start()
        {
        txtX.setText("");
        txtY.setText("");
        }
    }
copyright©2001 Prof Devi - mdevi@comine.com, mdevi@liu.edu. All rights reserved