了解匿名类并从 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/