Advertisement
Method | Description |
---|---|
public String getActionCommand() | Returns the name over the button, item or menuitem that was clicked to trigger the ActionEvent. |
public long getWhen() | Returns the time when an ActionEvent was generated. |
Method | Description |
---|---|
public void actionPerformed(ActionEvent ae) | Invoked when an Action Event is generated. |
Method | Description |
---|---|
public void addActionListener(ActionListener object) | where object is an object of the class that has implemented ActionListener interface and wanted to register itself to listen and respond to ActionEvent generated by a click on this specific source. |
Advertisement
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ActionEx1 implements ActionListener
{
Frame jf;
Button button1, button2;
Label label;
ActionEx1()
{
jf= new Frame("Button click events");
button1= new Button("Button1");
button2= new Button("Button2");
label = new Label();
jf.add(button1);
jf.add(button2);
jf.add(label);
//Registering the class ActionEx1 to listen to ActionEvent, when buttons are clicked.
button1.addActionListener(this); //this represents current object of ActionEx1 class.
button2.addActionListener(this);
jf.setLayout(new FlowLayout(FlowLayout.CENTER,60,10));
jf.setSize(250,150);
jf.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand().equals("Button1"))
{
label.setText("You've clicked Button1");
jf.add(label);
jf.setVisible(true);
}
if(ae.getActionCommand().equals("Button2"))
{
label.setText("You've clicked Button2");
jf.add(label);
jf.setVisible(true);
}
}
public static void main(String... ar)
{
new ActionEx1();
}
}
When you run the code, you are presented a window with two buttons shown in the Figure1 below -:
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement