Where would I implement the following code? By where I mean do I make a new class? Put it in the constructor of my main class? etc.
public interface ActionListener extends EventListener {
void actionPerformed(ActionEvent e);
}
Where would I implement the following code? By where I mean do I make a new class? Put it in the constructor of my main class? etc.
public interface ActionListener extends EventListener {
void actionPerformed(ActionEvent e);
}
You need to make a class that implements the interface.
public class ActionListenerExample implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// Do something here
}
}
You can then make an object of the class.
ActionListenerExample listener = new ActionListenerExample();
With Java 8, you could make this more compact by using a lambda expression.
ActionListener listener = action -> {
// Do something
};
If you don't use Java 8 (which you should) but still want to make it compact, use an anonymous class.
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Do something here
}
}
Here's an example implemented as a local variable:
final ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Hello World");
}};