java JavaFX - setOnAction 不适用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33986917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 22:22:16  来源:igfitidea点击:

JavaFX - setOnAction not applicable

javajavafx

提问by RAP

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:

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

btn.setOnAction(new EventHandler<ActionEvent>()

where it underlines setOnAction, and prints this Error:

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

 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?

我究竟做错了什么?

回答by RAP

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

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

import java.awt.event.ActionEvent;

with this

有了这个

import javafx.event.ActionEvent;

and you can also use lambda expression like this

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

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

回答by Reimeus

You're mixing up Javafx with Swing. Replace

您将 Javafx 与 Swing 混为一谈。代替

import java.awt.event.ActionEvent;

with

import javafx.event.ActionEvent;