Thursday, 4 August 2016

Command Button in java

A Command Button or Push Button is a component that contains a label and that generates an event when it is pressed.
Button defines these two constructors:
1. Button( )
2. Button(String str)
1. The first version creates an empty button.
2. 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:
1. void setLabel(String str)
2. String getLabel( )
Here, str becomes the new label for the button.

PROGRAM:-
// Demonstrate Buttons
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ButtonDemo" width=250 height=150>
</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);
}
}