0

I am getting a nullpointerexception and I don't understand why. Here is my code

public class AlertPane {
    @FXML
    public static Label msgLbl;
    @FXML
    private ImageView confirmBtn;
    @FXML
    private Pane alertPane;


    @FXML
    public void initialize() {
        alertPane.setVisible(true);
    }

    public static void display(String text) {
        try {
            Stage alertWindow = new Stage();
            Parent root = FXMLLoader.load(AlertPane.class.getResource("Alert.fxml"));
            Scene scene = new Scene(root);
            scene.getStylesheets().add(AlertPane.class.getResource("application.css").toExternalForm());
            alertWindow.setScene(scene);
            alertWindow.initStyle(StageStyle.UNDECORATED);
            alertWindow.initModality(Modality.APPLICATION_MODAL);
            alertWindow.show();
            msgLbl.setText(text); // THROWS A NULLPOINTEREXCEPTION
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

I have declared the controller for the Alert.fxml file which is the class itself(AlertPane) inside the scene builder.

Here is the Alert.fxml file :

<AnchorPane xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.AlertPane">
   <children>
      <Pane fx:id="alertPane" prefHeight="266.0" prefWidth="426.0" style="-fx-background-color: white;">
         <children>
            <Label fx:id="msgLbl" layoutY="86.0" prefHeight="94.0" prefWidth="426.0" style="-fx-alignment: center;" wrapText="true">
               <font>
                  <Font name="SAO UI TT Regular" size="19.0" />
               </font>
            </Label>
            <ImageView id="ico_alert" fx:id="confirmBtn" fitHeight="50.0" fitWidth="50.0" layoutX="362.0" layoutY="202.0" pickOnBounds="true" preserveRatio="true" style="-fx-cursor: hand;">
               <image>
                  <Image url="@../../../../Desktop/prog/mavis_lib/icons/ico_confirm.png" />
               </image></ImageView>
         </children>
      </Pane>
   </children>
</AnchorPane>
Chain Cross
  • 351
  • 1
  • 2
  • 12
  • `msgLbl` cannot be `static`. You need to do this without all these static stuff. – Jai Jun 28 '18 at 06:21
  • Why cant it be static? what do you suggest I do? – Chain Cross Jun 28 '18 at 06:23
  • Create an instance of `FXMLLoader`, and also create an instance of this controller. Then set the controller instance into the loader before you call `load()`. Change the constructor of your controller class to accept the `text` String, store it a private field and put that value into `msgLbl` in `initialize()`. – Jai Jun 28 '18 at 06:25

0 Answers0