【问题标题】:JavaFX - setOnAction not applicableJavaFX - setOnAction 不适用
【发布时间】:2015-11-29 19:17:30
【问题描述】:

我正在尝试学习 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();

    }
}

我做错了什么?

【问题讨论】:

  • 你导入了java.awt.event.ActionEvent你需要把它改成javafx.event.ActionEvent

标签: java javafx


【解决方案1】:

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

import java.awt.event.ActionEvent;

有了这个

import javafx.event.ActionEvent;

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

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

【讨论】:

  • 如果您觉得有帮助,请点赞并接受答案
【解决方案2】:

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

import java.awt.event.ActionEvent;

import javafx.event.ActionEvent;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    相关资源
    最近更新 更多