google search

Thursday, April 15, 2010

BUTTONS

USING BUTTONS

The most widely used control is the push button. A push button is a component that
contains a label and that generates an event when it is pressed. Push buttons are objects
of type Button. Button defines these two constructors:
Button( )
Button(String str)
The first version creates an empty button. The second creates a button that contains str
as a label.
After a button has been created, you can set its label by calling setLabel( ). You can
retrieve its label by calling getLabel( ). These methods are as follows:
void setLabel(String str)
String getLabel( )
Here, str becomes the new label for the button.
Handling Buttons
Each time a button is pressed, an action event is generated. This is sent to any listeners
that previously registered an interest in receiving action event notifications from that
component. Each listener implements the ActionListener interface. That interface defines
the actionPerformed( ) method, which is called when an event occurs. An ActionEvent
object is supplied as the argument to this method. It contains both a reference to the button
that generated the event and a reference to the string that is the label of the button. Usually,
either value may be used to identify the button, as you will see.
Here is an example that creates three buttons labeled “Yes,” “No,” and “Undecided.”
Each time one is pressed, a message is displayed that reports which button has been pressed. In this version, the label of the button is used to determine which button has
been pressed. The label is obtained by calling the getActionCommand( ) method on the
ActionEvent object passed to actionPerformed( ).
// Demonstrate Buttons
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*


*/
public class ButtonDemo extends Applet implements ActionListener {
String msg = "";
Button yes, no, maybe;
public void init() {
yes = new Button("Yes");
no = new Button("No");
maybe = new Button("Undecided");
add(yes);
add(no);
add(maybe);
yes.addActionListener(this);
no.addActionListener(this);
maybe.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
if(str.equals("Yes")) {
msg = "You pressed Yes.";
}
else if(str.equals("No")) {
msg = "You pressed No.";
}
else {
msg = "You pressed Undecided.";
}

repaint();
}
public void paint(Graphics g) {
g.drawString(msg, 6, 100);
}
}

0 comments:

  © Blogger templates ProBlogger Template by Ourblogtemplates.com 2008

Back to TOP