Button is an active component which is used to perform some operations such as saving the details into the database, deleting the details from the database, etc.
Creating a button is nothing but creating an object of Button class.
Button (); Button (String);
public void add ActionListener (ActionListener); public void remove ActionListener (ActionListener);
Write a java program to illustrate the concept of buttons?
Answer:
import java.awt.*; import java.awt.event.*; class BDemo extends Frame implements ActionListener { Button b1,b2,b3,b4; Label l; BDemo () { super ("BUTTON EXAMPLE...");// set title setSize (200,200); b1=new Button ("NORTH"); b2=new Button ("SOUTH"); b3=new Button ("EAST/EXIT"); b4=new Button ("WEST"); l=new Label (); l.setAlignment (Label.CENTER); add (b1,"North"); add (b2,"South"); add (b3,"East"); add (b4,"West"); add (l);// add at center of border layout by default b1.addActionListener (this); b2.addActionListener (this); b3.addActionListener (this); b4.addActionListener (this); setVisible (true); } public void actionPerformed (ActionEvent ae) { if (ae.getSource ()==b1) { System.out.println ("U HAVE CLICKED "+b1.getLabel ()); // String s1=b1.getLabel (); // l.setText (s1); l.setText (b1.getLabel ()); } if (ae.getSource ()==b2) { System.out.println ("U HAVE CLICKED "+b2.getLabel ()); l.setText (b2.getLabel ()); } if (ae.getSource ()==b3) { System.out.println ("U HAVE CLICKED "+b3.getLabel ()); l.setText (b3.getLabel ()); // System.exit (0); } if (ae.getSource ()==b4) { System.out.println ("U HAVE CLICKED "+b4.getLabel ()); l.setText (b4.getLabel ()); } }// actionPerformed };// BDemo class BDemo1 { public static void main (String [] args) { new BDemo (); } };
Output:
U HAVE CLICKED WEST U HAVE CLICKED SOUTH
U HAVE CLICKED EAST/EXIT U HAVE CLICKED NORTH
Steps for developing awt program:
This method provides functionality to GUI component.
Rewrite the above program using applets?
Answer:
import java.applet.Applet; import java.awt.*; import java.awt.event.*; /*<applet code="ButtonApp" height=200 width=200> </applet>*/ public class ButtonApp extends Applet implements ActionListener { Button b1, b2, b3, b4; Label l; public void init () { setLayout (new BorderLayout ()); b1=new Button ("North"); b2=new Button ("East"); b3=new Button ("West"); b4=new Button ("South"); l=new Label (); l.setAlignment (Label.CENTER); add (b1, "North"); add (b2, "East"); add (b3, "West"); add (b4, "South"); add (l); } public void Start () { b1.addActionListener (this); b2.addActionListener (this); b3.addActionListener (this); b4.addActionListener (this); } public void actionPerformed (ActionEvent ae) { if (ae.getSource ()==b1) { l.setLabel (b1.getLabel ()); } if (ae.getSource ()==b2) { l.setLabel (b2.getLabel ()); } if (ae.getSource ()==b3) { l.setLabel (b3.getLabel ()); } if (ae.getSource ()==b4) { l.setLabel (b4.getLabel ()); } } };
Steps for developing a FRAME application or APPLET application: