本文介绍了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 不适用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!