JavaFX-setOnAction不适用

The*_*ace 2 java javafx

我正在尝试学习JavaFX,并且已经编写了下面显示的代码,但是我似乎在使用以下代码行时遇到麻烦:

btn.setOnAction(new EventHandler<ActionEvent>()
Run Code Online (Sandbox Code Playgroud)

在强调setOnAction的位置并显示此错误:

 The method setOnAction(EventHandler<ActionEvent>) in the type ButtonBase is not applicable for the arguments (new EventHandler<ActionEvent>(){})
Run Code Online (Sandbox Code Playgroud)
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<ActionEvent>(){
             @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();

    }
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

RAP*_*RAP 5

您已经导入了awt事件监听器,只需更改此行代码

import java.awt.event.ActionEvent;
Run Code Online (Sandbox Code Playgroud)

有了这个

import javafx.event.ActionEvent;
Run Code Online (Sandbox Code Playgroud)

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

btn.setOnAction((event) -> {
  System.out.println("Button clicked");
});
Run Code Online (Sandbox Code Playgroud)