Java 在哪里实现ActionListener?
我将在哪里实现以下代码?我的意思是说我在哪里上新课?把它放在我的主类的构造函数中?等等Java 在哪里实现ActionListener?,java,interface,actionlistener,implements,Java,Interface,Actionlistener,Implements,我将在哪里实现以下代码?我的意思是说我在哪里上新课?把它放在我的主类的构造函数中?等等 public interface ActionListener extends EventListener { void actionPerformed(ActionEvent e); } 您需要创建一个实现接口的类 public class ActionListenerExample implements ActionListener { @Override public void ac
public interface ActionListener extends EventListener {
void actionPerformed(ActionEvent e);
}
您需要创建一个实现接口的类
public class ActionListenerExample implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// Do something here
}
}
然后可以创建该类的对象
ActionListenerExample listener = new ActionListenerExample();
使用Java8,您可以通过使用
如果您不使用Java8(您应该这样做),但仍希望使其紧凑,请使用
下面是一个作为局部变量实现的示例:
final ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Hello World");
}};
那么接口意味着什么呢?@zmi-An接口是一种类型(本质上是一个抽象类),它提供了类需要实现的方法的蓝图。接口提供行为的抽象,而实现类提供行为的实现。@zmi听起来像是你需要找到一个关于接口和类的简单教程。它可以实现为一个新类、一个内部类或一个匿名类,具体取决于你的需要,我希望它能帮助你
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Do something here
}
}
final ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Hello World");
}};