0

I don't know why this is not working. I want to set the text of a Label or Text. ( it does not matter which if it works). The label stays the same. When I use Text the application just crashes...

@FXML
    public Text txtMessage;
    @FXML
    public Text txtTitle;
    @FXML
    public Text txtResult;

    @FXML
    public Label lblResult;


    public void display(String title, String message) throws IOException {
        txtResult = new Text();
        lblResult = new Label();
        Stage stage = new Stage();
        stage.initModality(Modality.APPLICATION_MODAL);
        Parent root= FXMLLoader.load(getClass().getResource("/Alertbox.fxml"));
        lblResult.setText("message");

        stage.setTitle(title);
        stage.setScene(new Scene(root));
        stage.show();
    }

It has 2 parameters. I tried adding @FXML, or removing @FXML but both does not work. I also tried to initialize the label and text.


 txtResult = new Text();
 lblResult = new Label();

I debugged the code. message is a string and contains the right message.

  • 1
    You do not need to create new Text or Label, they are injected by the @FXML annotation and corresponding FXML file. – SephB Nov 01 '19 at 17:44
  • It still does not work if I remove the 'create new Text or Label' – jantje smith Nov 01 '19 at 18:09
  • What is in `Alertbox.fxml`? Also, is this class the controller for it? And, where do you set the text and what error message is the result? – tevemadar Nov 01 '19 at 18:11
  • Possible duplicate of [JavaFX new custom pop out window](https://stackoverflow.com/questions/37414441/javafx-new-custom-pop-out-window) – tevemadar Nov 01 '19 at 18:18
  • @tevemadar Yes that class is the controller for it. The class has a method called 'display'. The class does not have a constructor. Hmmm seems like I do not get errors. I just get warnings, but that are some other reasons – jantje smith Nov 01 '19 at 18:50

1 Answers1

0

Your controller should not be created when you call FXMLLoader.load as load will create the controller. You should also not use the static version of load. Your code should look somethink like:

public static ControllerClass display(String title, String message) throws IOException {
    Stage stage = new Stage();
    stage.initModality(Modality.APPLICATION_MODAL);
    FXMLLoader loader = new FXMLLoader();
    Parent root= loader.load(getClass().getResource("/Alertbox.fxml"));
    ControllerClass controller = loader.getController();    
    controller.lblResult.setText("message");
    stage.setTitle(title);
    stage.setScene(new Scene(root));
    stage.show();
    return controller;

}

This is still probably not exactly right, but it should point you in the correct direction.

Note, ControllerClass is the class name of your controller.

SephB
  • 617
  • 3
  • 6