JavaFX - setOnAction not applicable

2019-01-12 08:06发布

问题:

I am trying to learn JavaFX, and I've written the code shown down below, however I seem to be having trouble with this line of code:

btn.setOnAction(new EventHandler<ActionEvent>()

where it underlines setOnAction, and prints this Error:

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

    }
}

What am I doing wrong?

回答1:

You have imported awt event listener just change this line of code

import java.awt.event.ActionEvent;

with this

import javafx.event.ActionEvent;

and you can also use lambda expression like this

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


回答2:

You're mixing up Javafx with Swing. Replace

import java.awt.event.ActionEvent;

with

import javafx.event.ActionEvent;


标签: java javafx