0

I'm trying to make a confirmation box in JavaFX like in this video, but I want to load it from FXML because it is easier. The main method is supposed to call ask().

public class Controller {

    @FXML
    Label confirmLabel;
}


public class ConfirmBox {

    public static Stage confirmStage;
    public static boolean answer;
    private static final int WIDTH = 200;
    private static final int HEIGHT = 141;

    public static boolean ask(String title, String question) throws IOException {
        confirmStage = new Stage();
        confirmStage.initModality(Modality.APPLICATION_MODAL);
        AnchorPane confirmPane = (AnchorPane) FXMLLoader.load(ConfirmBox.class.getResource("ConfirmBox.fxml"));
    ERROR > Controller.confirmLabel.setText(question);
        Scene confirmScene = new Scene(confirmPane);
        confirmStage.setScene(confirmScene);
        confirmStage.showAndWait();
        return answer;
    }

}

Instead of opening the window, it gives tells me

Cannot make a static reference to the non-static field Controller.confirmLabel

How can I make it work?

Giorgos Myrianthous
  • 36,235
  • 20
  • 134
  • 156

1 Answers1

0

Your problem is at no time are you actually retrieving the controller for the FXML content your loading.

Instead try something like:

FXMLLoader loader = new FXMLLoader(ConfirmBox.class.getResource("ConfirmBox.fxml"));
AnchorPane confirmPane = (AnchorPane) FXMLLoader.load();
ConfirmControllerTYPE controller = loader.getController();
controller.confirmLabel.setText(question);

Where ConfirmControllerTYPE is the class of the controller for the FXML file.

  • in the line "AnchorPane confirmPane = (AnchorPane) FXMLLoader.load();" is says "Cannot make a static reference to the non-static method load() from the type FXMLLoader". – user10833006 Apr 07 '19 at 18:40