📜  actionListener java (1)

📅  最后修改于: 2023-12-03 14:59:11.013000             🧑  作者: Mango

ActionListener in Java

ActionListener is an interface in Java that is used for responding to events like button clicks, menu item selections, etc. It is a part of the java.awt.event package in Java SE.

How to implement ActionListener?

To implement ActionListener interface, follow the steps below:

  1. Import the ActionListener interface, along with other required interfaces and packages.

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
  2. Implement the ActionListener interface in your class.

    public class MyClass implements ActionListener {
        // code here
    }
    
  3. Override the actionPerformed() method of the ActionListener interface.

    @Override
    public void actionPerformed(ActionEvent e) {
        // code here to handle the event
    }
    
  4. Register an object of your class as a listener to the component that generates the event.

    JButton myButton = new JButton("Click me");
    myButton.addActionListener(new MyClass());
    
Example

Let's implement an ActionListener for a JButton in Java.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

public class ActionListenerExample implements ActionListener {

    public static void main(String[] args) {
        JFrame frame = new JFrame("ActionListener Example");
        JButton button = new JButton("Click me");
        button.addActionListener(new ActionListenerExample());
        frame.add(button);
        frame.pack();
        frame.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Button clicked!");
    }
}

In the above example, we create a JFrame with a JButton. We register an object of ActionListenerExample as a listener to the JButton using the addActionListener() method. When the button is clicked, the actionPerformed() method is called and it prints "Button clicked!" on the console.

Conclusion

ActionListener in Java is used to handle events like button clicks, menu item selections, etc. It is implemented by overriding the actionPerformed() method of the ActionListener interface. An object of the class is registered as a listener to the component that generates the event using the addActionListener() method.