Friday, 31 August 2012

Calculator Demo



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

      public class Cal extends Applet implements ItemListener,ActionListener
     {
              Button b1;
              Label l1,l2,l3;
             TextField t1,t2,t3;
             Checkbox c1,c2,c3,c4;
             CheckboxGroup cbg; String msg="";
             long a,b;

           public void init()
          {
                l1=new Label("First Number:");
                l2=new Label("Second Number:");
                l3=new Label("The Result Is:");

                t1=new TextField(6);
                t2=new TextField(6);
                t3=new TextField(12);

               b1=new Button("Calculate");
              cbg=new CheckboxGroup();

              c1=new Checkbox("Add",cbg,true);
              c2=new Checkbox("Sub",cbg,false);
              c3=new Checkbox("Mul",cbg,false);
              c4=new Checkbox("Div",cbg,false);

             setLayout(new GridLayout(6,6));
               add(l1); add(t1); add(l2); add(t2);
               add(l3); add(t3);
               add(c1); add(c2); add(c3); add(c4);
              add(b1);
            b1.addActionListener(this);
            c1.addItemListener(this);
            c2.addItemListener(this);
      
 c3.addItemListener(this);
             c4.addItemListener(this);
       }
     public void actionPerformed(ActionEvent e)
      {
            msg=e.getActionCommand();

            a=Integer.parseInt(t1.getText());
            b=Integer.parseInt(t2.getText());

        if(msg.equals("Calculate"))
        {
            if("Add".equals(cbg.getSelectedCheckbox().getLabel()))
                      t3.setText(String.valueOf(a+b));

          else if("Sub".equals(cbg.getSelectedCheckbox().getLabel()))
                     t3.setText(String.valueOf(a-b));

          else if("Mul".equals(cbg.getSelectedCheckbox().getLabel()))
                      t3.setText(String.valueOf(a*b));

          else if("Div".equals(cbg.getSelectedCheckbox().getLabel()))
                     t3.setText(String.valueOf(a/b));
        }   
       repaint();  

     }

     public void itemStateChanged(ItemEvent e)
     {
       repaint();
     }
 }

 /*<applet code="Cal.java" width=300 height=250>
    </applet> */

No comments:

Post a Comment