Monday, 17 September 2012

Handle more than one button event in java

In computer science an event is an action that is usually initiated outside the scope of a program and that is handled by a piece of code inside the program. GUI based programming is based on event, if you want handle event of a button in java (Applet,Swing) then you have to use ActionListener interface and implements actionPerformed funtion.We use more than one button in java program for handle each button event individually for achieve this we mustidentified each button event uniquely. You can identified button by its name or its text value, text value is not good becouse there can be same text on more than one button. Getting Button name is more usefull conside following program.....
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonEventDemo extends Applet implements ActionListener
{  
       Button bt1,bt2,bt3;   Label lbl;  
       public void init() 
       {     
            bt1=new Button("Button1");   
            bt2=new Button("Button2");
            bt3=new Button("Button3");     
           lbl=new Label("Label");    
           Add(bt1);        Add(bt2);      
           Add(bt3);        Add(lbl);      
           bt1.addActionListener(this);     
           bt2.addActionListener(this);        
           bt3.addActionListener(this);  
      } 
      public void actionPerformed(ActionEvent e)
      {     
           // String s=e.getActionCommand();       
          // if(s=="Button1")     
          //  {      
         //             lbl.setText("Clicked Button 1");   
         //   }       
         //   else     
         //   {      
         //             lbl.setText("Clicked Button 2");     
        //    }         
             Object ob=e.getsource();           
             if(ob.equals(bt1)                
                 lbl.setText("Clicked Button 1");      
             else          
             {                
                   if(ob.equals(bt2)                   
                      lbl.setText("Clicked Button 2");                 
                  else                       
                       lbl.setText("Clicked Button 3");           
              }
         }

                  
String s=e.getActionCommand();
this command will set text of control which create control in s e.g.  if button clicked then s will hold Button1 textso we can check control text to uniquely identified a control but its not so good because there can be same text of more than one control.                 
                Object ob=e.getsource();
this line initialize ob with Button reference which name is bt1 if bt1 is clicked otherwise other control instanceso it is useful  to uniquely identified button because button name always unique in a program . 

2 comments:

  1. if i want to get reference of multiple buttons,can i store it in an object array??

    ReplyDelete