我选择了一个单击鼠标时在屏幕上打印“Hello World”的基本示例代码如下。
package sample;
import javafx.application.Application;
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;
/**
*
* @author gauravp
*/
public class Sample extends Application {
/**
* @param args the command line arguments
*/
Button btn = new Button("ok");
//Label l = new Label("Done");
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("First Stage");
//Created anonymous inner class EventHandler<ActionEvent>
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.print("Hello World !!");
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
}
在文档中提到 EventHandler 是一个 interface ,但是如何实例化接口(interface)......
“新事件处理程序
在很多困惑中....如果你有任何想法请回复..这是链接 对于 EventHandler 接口(interface): http://docs.oracle.com/javafx/2.0/api/javafx/event/EventHandler.html
最佳答案
语法
new EventHandler<ActionEvent>() {
@Override // <- notice the annotation, it overrides from the interface.
public void handle(ActionEvent event) {
System.out.print("Hello World !!");
}
}
创建一个实现 EventHandler 的“匿名内部类”,并定义 handle 方法。如果您检查编译项目时生成的类,您可能会发现一个名为 Sample$1(或类似文件)的类文件,它是为此代码生成的类。
您可以在这里阅读内部(匿名)类:http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html
回答你的问题:EventHandler 是一个接口(interface),这段代码实际上并没有创建它的实例,而是新声明的匿名类的实例。
关于java - JavaFX 中的 EventHandler<T extends Event> 类或接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8938769/