gpt4 book ai didi

JavaFX - setOnAction 不适用

转载 作者:行者123 更新时间:2023-12-02 00:33:17 24 4
gpt4 key购买 nike

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

btn.setOnAction(new EventHandler<ActionEvent>()

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

}
}

我做错了什么?

最佳答案

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

import java.awt.event.ActionEvent;

有了这个

import javafx.event.ActionEvent;

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

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

关于JavaFX - setOnAction 不适用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33986917/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com