JavaFX - setOnAction不适用 [英] JavaFX - setOnAction not applicable

查看:134
本文介绍了JavaFX - setOnAction不适用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>()

在哪里强调setOnAction,并打印此错误:

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();

    }
}

我做错了什么?

推荐答案

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

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

import java.awt.event.ActionEvent;

这个

import javafx.event.ActionEvent;

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

and you can also use lambda expression like this

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

这篇关于JavaFX - setOnAction不适用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆