• Java Button Class

    Java Button Class

    Java Button Class component is a control that has a label and generates an event when pressed. When a button is pressed and released, AWT sends an instance of ActionEvent to the button, by calling processEvent on the button. The button’s processEvent method receives all events for the button; it passes an action event along by calling its own processActionEvent method. The latter method passes the action event on to any action listeners that have registered an interest in action events generated by this button. If an application wants to perform some action based on a button being pressed and released, it should be implement ActionListener and register the new listener to receive events from this button, by calling the button’s addActionListener method. The application can make use of the button’s action command as a messaging protocol.

    Java Button Example Code

    /*Make an Applet that Create Two Buttons named “Red” and “Blue” when a button is
    pressed the background color of the applets is set to the color named by that button’s label.*/

    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;

    public class ButtonApplet extends Applet implements ActionListener {

    Button btnRed, btnBlue;

    public void init() {

    btnRed = new Button(“Red”);
    btnBlue = new Button(“Blue”);
    add(btnRed);
    add(btnBlue);

    btnRed.addActionListener(this);
    btnBlue.addActionListener(this);
    }

    public void actionPerformed(ActionEvent ae){

    if(ae.getSource() == btnRed)
    setBackground(Color.red);
    else if(ae.getSource() == btnBlue)
    setBackground(Color.blue);
    }
    }

    Output:

    Java Button Class Example

    Figure: Java Button Class Example

    Appreciate my work :Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInPin on PinterestShare on RedditShare on StumbleUponShare on TumblrDigg thisShare on YummlyShare on VKFlattr the authorBuffer this page

Leave a Reply

Your email address will not be published. Required fields are marked *