Saturday 7 July 2012

program that describe use of ActionListener interface in applet

import java.lang.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="text" width=200 height=200>
</applet>
*/
 public class text extends Applet implements ActionListener
{
    Label lbl1,lbl2;
    TextField txt1,txt2;
    Button b;
    String s;
      public void init()
      {
       lbl1=new Label("Text1");
       txt1=new TextField(10);
       lbl2=new Label("Text2");
       txt2=new TextField(20);
        b=new Button("Enter");
        add(lbl1); 
        add(txt1); 
        add(lbl2); 
        add(txt2);
         add(b); 
        txt1.addActionListener(this);
        txt2.addActionListener(this);
        b.addActionListener(this);
       }
        public void actionPerformed (ActionEvent ae)
       { int n1,n2,ans;
    try
    {
    n1=Integer.parseInt(txt1.getText());
    n2=Integer.parseInt(txt2.getText());
    ans=n1+n2;
    s="Addition of n1 ans n2  is "+ ans;
    repaint();
    }
    catch(NumberFormatException e)
    {
       
    s=txt1.getText()+" "+txt2.getText();
    repaint();
    }
       }
       public void paint(Graphics g)
       {
        g.drawString(s,100,100);
     

       }
}

No comments:

Post a Comment