3.2.1 Action Event
3.2.1 Action Event
ActionEvent-
-defined in java.awt.event package.
-The ActionEvent is generated when button is clicked or the item of a list is double clicked.
Constructors-
1. ActionEvent(Object source, int id, String command)- Constructs an ActionEvent object.
2. ActionEvent(Object source, int id, String command, int modifiers) - Constructs an
ActionEvent object with modifier keys.
3. ActionEvent(Object source, int id, String command, long when, int modifiers)- Constructs an
ActionEvent object with the specified modifier keys and timestamp
Methods-
1. String getActionCommand()- Returns the command string associated with this action.
ActionListener-
-interface is found in java.awt.event
-used to receive action event.
-the respective class which wants to handle action event implements this interface, and the object
created with that class is registered with a component using the components addActionListener method
i.e register listener syntax- compobj.addActionListener(Eventclass e)
-When the action event occurs that object action performed method is invoked.
Method-
1. public abstract void actionPerformed(ActionEvent e)-
-The actionPerformed() method is invoked automatically whenever you click on the registered
component.
Develop a program to implement action event
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class action extends Applet implements ActionListener
{
Button b1; Label l1;
public void init()
{
b1=new Button("Ok");
l1=new Label("Press Ok button");
setLayout(new FlowLayout(FlowLayout.RIGHT));
add(l1); add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
l1.setText("U Have pressed ok button");
}
}
/* <applet code=action.class height=300 width=300> </applet> */
Develop a program to implement action event
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class action121 extends Applet implements ActionListener
{
Button b1; String s;
public void init()
{
b1=new Button("Ok");
setLayout(new FlowLayout(FlowLayout.RIGHT));
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{ s="U Have pressed ok button"; }}
public void paint(Graphics g)
{ g.drawString(s,10,20); }
}