【问题标题】:JavaFx button event handler,cannot be resolved as a variableJavaFx 按钮事件处理程序,无法解析为变量
【发布时间】:2018-02-25 22:55:39
【问题描述】:

在handle 方法中它说executeButton 不能在handle 方法中解析。这是为什么?我是 javafx 的新手。我按照 youtube 上的教程提示我做了所有事情。这不是一个完整的代码,只是一个近似值

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import javafx.event.EventHandler;
import javafx.event.ActionEvent;

public class BankApplication extends Application implements 
EventHandler<ActionEvent>{

public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception {

    Button executeButton = new Button("Execute");
    executeButton.setOnAction(this);        

}

@Override
public void handle(ActionEvent event) {
    if (event.getSource() == executeButton) {

    }
}

}

【问题讨论】:

  • 基本变量范围 101:局部变量在声明它们的方法之外不可见。如果您想从handle 方法访问它,您需要将executeButton 更改为一个字段。或者你只是使用不同的EventHandlers 来触发不同的效果,不需要检查来源。

标签: java javafx event-handling handle


【解决方案1】:

将按钮变成一个实例变量,以便可以从事件处理程序中访问它。

public class BankApplication extends Application implements
    EventHandler<ActionEvent> {
private Button executeButton = new Button("Execute");

public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception {

    executeButton.setOnAction(this);

}

@Override
public void handle(ActionEvent event) {
    if (event.getSource() == executeButton) {

    }
}
}

【讨论】:

    猜你喜欢
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    相关资源
    最近更新 更多