java actionlistener
ActionListener
is an interface in the Java programming language that defines a listener for action events. An action event occurs whenever an object (usually a GUI component like a button) is activated (i.e., clicked, pressed, etc.). An ActionListener
receives notification of an action event and can then perform some action in response to that event.
To use an ActionListener
, you typically create an instance of a class that implements the ActionListener
interface and then register it with the component that generates the action events. For example, to create an ActionListener
for a button, you might write:
button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Perform some action in response to the event } });
This code creates an anonymous inner class that implements the ActionListener
interface and defines the actionPerformed
method. This method is called whenever the button is clicked, and can be used to perform some action (e.g., update a label, open a file, etc.).
In Java 8 and later, you can use lambda expressions to define ActionListener
instances more concisely. For example:
button.addActionListener(e -> { // Perform some action in response to the event });
This code creates a lambda expression that is equivalent to the anonymous inner class in the previous example.