Handling Button in java
In this example we are going to control Button.
To control the button we are using three type of package. One is java.awt.* second is java.applet.*
and third is java.awt.event.*; .The java.awt.* is used for
GUI interface. AWT classes are contain in this package. The java.applet.*
package is used to create an applet and java.awt.event.*; defined
within the java.awt.*; package is a subclass of EventObject.
It is a super class of all AWT-based event..
Button defines two constructors:
Button(): Is use to create an empty button.
Button (String str) : Is use to create a button
that contains String str as label.
Action Listner() defines one method to receive
action event.
Each time a button is pressed ,an action is
generated. this is send to any listeners that previously registered an interest
in receiving action from that component.
In our example first we implement ActionListener()
each listener implement the ActionLinstner.
When the button is pressed or an event is
occur ActionPerformed() interface is called.
In our example we creates four button Jan,
Nov, Dec, Feb. Each time one is pressed a message is
displayed that report which button has been pressed. The label
of the button is used to determine which button has been
pressed.
The label is obtained by calling the
get.ActionCommand() method on the ActionEvent object passed to
actionPerformed().
//creat Button
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="ButtonDemo" width=300 height=200>
</applet>
*/
public class ButtonDemo extends Applet implements ActionListener{
String msg="which is the last month ?";
Button one,two,three,four;
public void init()
{
one = new Button("Jan");
two = new Button("Nov");
three = new Button("Dec");
four = new Button("Feb");
add(one);
add(two);
add(three);
add(four);
one.addActionListener(this);
two.addActionListener(this);
three.addActionListener(this);
four.addActionListener(this);
}
public void actionPerformed(ActionEvent ae){
String str=ae.getActionCommand();
if(str.equals("Jan")){
msg="Your answer is Jan";
}
else if(str.equals("Nov")){
msg="Your answer is Nov";
}
else if(str.equals("Dec")){
msg="Your answer is Dec";
}
else if(str.equals("Feb")){
msg="Your answer is Feb";
}
repaint();
}
public void paint(Graphics g){
g.drawString(msg,6,100);
}}
|
Download Source Code
Output Of Example
