JavaFX NullPointerException其他类中的按钮

时间:2016-11-28 13:14:11

标签: javafx nullpointerexception

我为学校项目创建了一个应用程序。登录后,您应该转到仪表板。这可行,但是,当我尝试将按钮设置为禁用时,它会抛出NullPointerException。

在此文件中,舞台正在更改(登录后):

public class ScreenController {
    public void setScene(Stage stage, Parent root,Button button, String file){
        if(file == "dashboard"){
            stage = (Stage) button.getScene().getWindow();
            try {
                root = FXMLLoader.load(getClass().getResource("Dashboard.fxml"));
            } catch (IOException ex) {
                System.out.println("IOException: "+ex);
            }
            Scene scene = new Scene(root);
            stage.setTitle("Corendon - Dashboard");
            stage.setScene(scene);

            stage.show();
            Dashboard dashboard = new Dashboard();
        }
    }
}

在最后一行,该按钮应设置为禁用...

Dashboard dashboard = new Dashboard();

......这个班级:

public class Dashboard extends ScreenController {
    @FXML public Button buttonDashboard1;

    public Dashboard(){
        buttonDashboard1.setDisable(true);
    }
}

但这不起作用它会抛出NullPointerException:

Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
    at 
...
Caused by: java.lang.NullPointerException
    at fastenyourseatbelts.Dashboard.<init>(Dashboard.java:11)
    at fastenyourseatbelts.ScreenController.setScene(ScreenController.java:33)
    at fastenyourseatbelts.LoginController.buttonLogin(LoginController.java:74)
    ... 59 more

我现在尝试了几个小时,但我没有得到解决方案......有谁知道出了什么问题,为什么会这样?

1 个答案:

答案 0 :(得分:0)

将代码从控制器的构造函数移动到initialize。注入所有字段后,FXMLLoader调用此方法,因此应该可以访问buttonDashboard1实例:

public class Dashboard extends ScreenController {
    @FXML public Button buttonDashboard1;

    @FXML
    private void initialize() {
        buttonDashboard1.setDisable(true);
    }
}

您还必须确保在fxml文件的根元素中指定控制器,例如(将packagename替换为Dashboard类的包)

<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="packagename.Dashboard">
    <children>
        <Button text="click me" fx:id="buttonDashboard1"/>
    </children>
</VBox>

或在加载之前设置为fxml的控制器:

FXMLLoader loader = new FXMLLoader(getClass().getResource("Dashboard.fxml"));
Dashboard dashboard = new Dashboard();
loader.setController(dashboard);
root = loader.load();

(在这种情况下,不要使用fx:controller属性)