除非通过处理程序方法进行交互,否则FXML对象都为null。

时间:2018-08-21 11:29:39

标签: java javafx nullpointerexception fxml

我正在编写一个简单的应用程序,该功能可以统计功能中的饮料计数。我正在使用Java并用FXML编写GUI。

我遇到的一个问题是,除非我通过处理程序方法与之交互,否则所有@FXML对象都为null。

@FXML
private Label directoryLabel; // the label in question

public SettingsWindow() {
    super();
}

@Override
protected void Refresh() {
    PriorityLogger.Log("Settings Window Refreshed.", PriorityLogger.PriorityLevel.Low);
    // returns a null pointer exception
    directoryLabel.setText(ApplicationSettings.GetInstance().GetTextFileDirectory());

}

@FXML
public void HandleDirectoryChangeButton(ActionEvent event) {
    PriorityLogger.Log("Handling directory change", PriorityLogger.PriorityLevel.Low);
    // works perfectly fine
    directoryLabel.setText(ApplicationSettings.GetInstance().GetTextFileDirectory());
}

如您在上面看到的,尝试通过Refresh()方法更改文本;在计时器上调用它会导致空指针异常。但是,如果我尝试通过按钮上的handler方法更改文本,则一切正常。

这是一个令人困扰的问题,它将在整个应用程序开发过程中影响我,而我正努力寻找具体的解决方法或解释其原因。

有人可以帮助我吗?

谢谢, 康纳。

更新:

这是我获取实例的方式:

public class WindowLoader<T extends Window> {

public T NewWindow(String fxml, Class<T> windowClass) throws InstantiationException, IllegalAccessException {
    Stage stage = new Stage();
    return NewWindow(fxml, windowClass, stage);
}

public T NewWindow(String fxml, Class<T> windowClass, Stage stage) throws InstantiationException, IllegalAccessException {
    try {
        Parent root = FXMLLoader.load(getClass().getResource(fxml));
        Scene scene = new Scene(root);
        stage.setScene(scene);
    } catch (IOException ex) {
        PriorityLogger.Log("ERROR: Window Loader couldn't load your window - " + ex.toString(), PriorityLogger.PriorityLevel.High);
    }
    T t = windowClass.newInstance();
    t.SetStage(stage);
    return t;
}

}

 private void SetupSettingsWindow() {
    WindowLoader windowLoader = windowLoaderFactory.getWindowLoader();
    try {
        settingsWindow = (SettingsWindow) windowLoader.NewWindow("SettingsWindowFXML.fxml", com.albinodevelopment.View.SettingsWindow.class);
        settingsWindow.start();
    } catch (InstantiationException | IllegalAccessException ex) {
        PriorityLogger.Log("ERROR; Couldn't load settings window for some reason - " + ex.toString(), PriorityLogger.PriorityLevel.High);
    }
}

当他们按下菜单栏上的按钮时,就会从我的MainWindow中调用SetupupSettingsWindow。

0 个答案:

没有答案
相关问题