Friday 9 September 2016

Handle Action Events for AWT Button Example

  1. /*
  2.         Handle Action Events for AWT Button Example
  3.         This java example shows how to handle action event of AWT Button by implementing
  4.         ActionListener interface.
  5. */
  6.  
  7. import java.applet.Applet;
  8. import java.awt.Button;
  9. import java.awt.Graphics;
  10. import java.awt.event.ActionEvent;
  11. import java.awt.event.ActionListener;
  12.  
  13. /*
  14. <applet code="HandleActionEventExample" width=200 height=200>
  15. </applet>
  16. */
  17.  
  18. public class HandleActionEventExample extends Applet implements ActionListener{
  19.  
  20.         String actionMessage="";
  21.        
  22.         public void init(){
  23.                 //create Buttons
  24.                 Button Button1 = new Button("Ok");
  25.                 Button Button2 = new Button("Cancel");
  26.                
  27.                 //add Buttons
  28.                 add(Button1);
  29.                 add(Button2);
  30.                
  31.                 //set action listeners for buttons
  32.                 Button1.addActionListener(this);
  33.                 Button2.addActionListener(this);
  34.         }
  35.        
  36.         public void paint(Graphics g){
  37.                 g.drawString(actionMessage,10,50);
  38.         }
  39.        
  40.         public void actionPerformed(ActionEvent ae){
  41.                
  42.                 /*
  43.                  * Get the action command using
  44.                  * String getActionCommand() method.
  45.                  */
  46.                
  47.                 String action = ae.getActionCommand();
  48.                
  49.                 if(action.equals("Ok"))
  50.                         actionMessage = "Ok Button Pressed";
  51.                 else if(action.equals("Cancel"))
  52.                         actionMessage = "Cancel Button Pressed";
  53.                
  54.                 repaint();
  55.         }
  56. }
     

No comments: