作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试学习 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/
我是一名优秀的程序员,十分优秀!