我应该在哪里实现以下代码?我的意思是我在哪里创建一个新类?把它放在我的主类的构造函数中?等等
public interface ActionListener extends EventListener {
void actionPerformed(ActionEvent e);
}
最佳答案
您需要创建一个实现该接口(interface)的类。
public class ActionListenerExample implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// Do something here
}
}
然后您可以创建该类的对象。
ActionListenerExample listener = new ActionListenerExample();
使用 Java 8,您可以使用 lambda expression 使其更加紧凑。 .
ActionListener listener = action -> {
// Do something
};
如果您不使用 Java 8(您应该使用 Java 8)但仍希望使其紧凑,请使用 anonymous class .
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Do something here
}
}
关于java - 我应该在哪里实现 ActionListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36024098/