JavaFX – setOnAction不适用

我正在尝试学习JavaFX,并且我已经编写了下面显示的代码,但是我似乎遇到了这行代码的问题:

btn.setOnAction(new EventHandler() 

它下划线setOnAction,并打印此错误:

  The method setOnAction(EventHandler) in the type ButtonBase is not applicable for the arguments (new EventHandler(){}) 
 import java.awt.event.ActionEvent; import javafx.application.Application; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class Test 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(){ @Override public void handle(ActionEvent event) { System.out.println("Button clicked"); } }); StackPane root = new StackPane(); root.getChildren().add(btn); primaryStage.setScene(new Scene(root, 300, 250)); primaryStage.show(); } } 

我究竟做错了什么?

您已导入awt事件侦听器只需更改此行代码

 import java.awt.event.ActionEvent; 

有了这个

 import javafx.event.ActionEvent; 

你也可以像这样使用lambda表达式

 btn.setOnAction((event) -> { System.out.println("Button clicked"); }); 

你把Javafx与Swing混在一起。 更换

 import java.awt.event.ActionEvent; 

 import javafx.event.ActionEvent;