Saturday 30 June 2012

program to design applet with two Text boxes and a Button.If both Text boxes contain a Number then add two numbers. If both contain String then concate otherwise raise user defined Exception in java.

import java.awt.event.*;
import java..*;
import java.awt.*;
import java.io.*;
/*
<applet code="Exception" width=700 height=300>
</>
*/
public class Exception extends Applet implements ActionListener
{
  String msg=" ",msg1=" ",sum=" ",con=" ";
  String str3;
  Button  Press;
  TextField  T1,T2;
  int n1,n2,ans;
 
    public void init()
     {
       setFont(new Font("Times New Roman",Font.PLAIN,15));
        
       Label  L1=new Label("Enter No. Or String : ",Label.RIGHT);
       T1=new TextField(15);
       Label  L2=new Label("Enter No. Or String : ",Label.RIGHT);
       T2=new TextField(15);
       Press=new Button("ADD/CONCATE");
        
       add(L1);
       add(T1);
       add(L2);
       add(T2);
       add(Press);
       
       T1.addActionListener(this);
       T2.addActionListener(this);
       Press.addActionListener(this);
     }
    public void start()
     {
       msg="NO STRINGS ARE ENTERED....";
       msg1="NO NUMBERS ARE FOUND.....";
     }
       
    public void actionPerformed(ActionEvent ae)
     {

       String s1=ae.getActionCommand();
       String s2=ae.getActionCommand();
       s1=T1.getText();
       s1=s1.trim();
       s2=T2.getText();
       s2=s2.trim();

       try
       {
         n1=Integer.parseInt(s1);
         n2=Integer.parseInt(s2);

         ans=n1+n2;
         con="RESULT FOR CONCATATION";
         sum="RESULT FOR ADDITION";
         msg="THIS TIME ADDITION IS PERFORMED....";
         msg1="YOUR SUM OF ENTERED NO.IS  :  "+ans;
         repaint();
 
       }catch(NumberFormatException nf)


         {
          str3=s1+s2;
          sum="RESULT FOR ADDITION";
          con="RESULT FOR CONCATATION";
          msg="CONCATED STRING IS :  "+str3;
          msg1="THIS TIME CONCATATION IS PERFORMED.....";
          repaint(); 
         }
      }
    public void paint(Graphics g)
     {
       setBackground(Color.blue);
       setForeground(Color.white);

       g.drawString(sum,395,105);
       g.drawString(con,35,105);    
       g.drawString(msg1,375,150);
       g.drawString(msg,10,150);
     }
}

No comments:

Post a Comment