java - 如何将匿名Java类重写为非匿名类?

标签 java anonymous-class

了解匿名类并从 Oracle 获得此知识。我希望有人能告诉我,如果我不使用匿名类,这会是什么样子。我该如何用一个新类来做到这一点?

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class HelloWorld extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello World!");
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
            }
        });

        StackPane root = new StackPane();
        root.getChildren().add(btn);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }
}

In this example, the method invocation btn.setOnAction specifies what happens when you select the Say 'Hello World' button. This method requires an object of type EventHandler. The EventHandler interface contains only one method, handle. Instead of implementing this method with a new class, the example instead uses an anonymous class expression. Notice that this expression is the argument passed to the btn.setOnAction method.

来源:http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

最佳答案

只需在某处创建一个新的非匿名类即可。我将其作为 HelloWorld 中的嵌套类进行:

public class HelloWorld extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello World!");
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new MyEventHandler());

        StackPane root = new StackPane();
        root.getChildren().add(btn);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }

    public class MyEventHandler implements EvenHandler<ActionEven>
    {
        @Override
        public void handle(ActionEvent event) {
            System.out.println("Hello World!");
        }
    }
}

关于java - 如何将匿名Java类重写为非匿名类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18594980/

相关文章:

java - xml 中的 DTD 如何使使用 java DOM 更容易解析?

java - Findviewbyid 找不到按钮

java - 使用插件将消息从 Bukkit 服务器传输到 IRC

java - JNI/安卓 : call to non static method in Java from C++?

java - 具有匿名类型构造函数的对象类

java - 如何在eclipse中设置fileInputStream的文件路径

java - 是否可以向匿名类添加属性而不是仅覆盖其方法?

java - 如何传递或分配在 runOnUiThread 中获得的值

kotlin - 从回调 kotlin 获取值

java - 修改匿名内部类的局部变量