Master Java’s ActionListener interface to handle action events
ActionListener,The ActionListener interface is used for dealing with action events.
For example, it is utilized by a JButton for button clicks, by JCheckbox for checking and unchecking, by means of a JMenuItem while an option is picked and many other graphical components.
It’s a simple interface with most effective one technique:
public interface ActionListener extends EventListener{
public void actionPerformed(ActionEvent e);
}
To use the ActionListener interface, it must be carried out via a class.
There are numerous approaches to do this — growing a new class, the usage of the magnificence the graphical issue is in, using an internal elegance or the usage of an nameless internal class.
The code that wishes to be run whilst the motion occasion occurs is placed within the actionPerformed method.
Then the magnificence implementing the interface must be registered with the graphical element thru the addActionListener approach.
or instance, the following class implements the elegance and the JButton uses the class to address its button click on events:
public class SimpleCalc implements ActionListener{
public SimpleCalc()
{
JButton aButton = new JButton("A Button");
aButton.setActionCommand("A Button);
aButton.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
//put code to run on the button click here
}
}
See the simple calculator handling button events for a step-with the aid of-step instance of the usage of enforcing an through the usage of the containing magnificence, an inner magnificence, and an anonymous magnificence.
The complete Java code listing can be found in a easy calculator instance application.