Addactionlistener new actionlistener

Here is an example of how to add an ActionListener to a component in Java:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ActionListenerExample {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame("ActionListener Example");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                JPanel panel = new JPanel();
                JButton button = new JButton("Click me!");
                button.addActionListener(new MyActionListener());
                panel.add(button);

                frame.add(panel);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }

    static class MyActionListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            System.out.println("Button clicked!");
        }
    }
}

In this example, we create a JFrame and a JPanel with a JButton. We then add an ActionListener to the button using the addActionListener method. The ActionListener is an instance of the MyActionListener class, which implements the ActionListener interface.

When the button is clicked, the actionPerformed method of the MyActionListener class is called, which prints "Button clicked!" to the console.

Note that the ActionListener is added to the button using the SwingUtilities.invokeLater method, which ensures that the GUI is created and updated on the Event-Dispatching Thread (EDT). This is a good practice to follow when working with Swing components.