java.lang.NullPointerException it works, but error. Trying to find the error

762 Views Asked by At

I have an error when I click "start button", it loads me a new fxml where I will play with it, it works fine, but console says me this error.. I cannot understand how to solve it.

My FXML: (Look only to startGame, that gives me some problems)

    public class StartImageController implements Initializable {

   @FXML
   private MenuBar myMenuBar;
   private AudioClip audio;
   private AudioClip beep;

   @Override
   public void initialize(URL url, ResourceBundle rb) {
      audio = new AudioClip(getClass().getClassLoader().getResource("othello/music/background_music.wav").toExternalForm());
      beep = new AudioClip(getClass().getClassLoader().getResource("othello/music/button.wav").toExternalForm());
      audio.stop();
      audio.setVolume(0.2);
      audio.setCycleCount(INDEFINITE);
      audio.play();
   }


   //Metodo per chiudere l'intero programma
   @FXML
   private void exitProgram(ActionEvent event) {
      System.exit(0);
   }


   //Metodo per chiudere solo lo stage
   private void exitStage(ActionEvent event){
      ((Node)(event.getSource())).getScene().getWindow().hide();
   }

   //Metodo per far partire la musica da menu item
   @FXML
   public void audioY(ActionEvent e)throws IOException{
      audio.stop();
      audio.setVolume(0.2);
      audio.setCycleCount(INDEFINITE);
      audio.play();
   }

   //Metodo per togliere la musica da menu item
   @FXML
   public void audioN(ActionEvent e)throws IOException{
      audio.stop();
   }

   //Metodo per tema dark
   @FXML
   public void darkTheme(ActionEvent event) throws IOException {
      //fermo la canzone del tema light e avvio la canzone del tema dark
      audio.stop();
      Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("othello/view/startImageDark.fxml"));
      Scene scene = new Scene(root);
      Stage stage = (Stage) myMenuBar.getScene().getWindow();
      stage.setScene(scene);
      stage.show();
   }

   //Metodo per far partire la sessione di gioco
   @FXML
   public void startGame(ActionEvent event) throws IOException {
      beep.play();
      Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("othello/view/board.fxml"));
      Scene scene = new Scene(root);
      scene.getStylesheets().add("othello/view/lightTheme.css");

      //la scena entra in fade
      FadeTransition ft = new FadeTransition(Duration.millis(3000), root);
      ft.setFromValue(0.0);
      ft.setToValue(1.0);
      ft.play();

      Node node=(Node) event.getSource();
      Stage stage=(Stage) node.getScene().getWindow();

      audio.stop();
      stage.setResizable(false);
      stage.setTitle("Othello - Game session");
      stage.setScene(scene);
      stage.show();
   }


   //Metodo per visualizzare le istruzioni da menu item
   @FXML
   public void showInstruction(ActionEvent event) throws IOException {
      Stage primaryStage = new Stage();
      Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("othello/view/instruction.fxml"));
      Scene scene = new Scene(root);

      primaryStage.setScene(scene);
      primaryStage.setResizable(false);
      primaryStage.sizeToScene();
      primaryStage.setTitle("Instruction");
      primaryStage.show();
   }


   //Metodo per visualizzare about da menu item
   @FXML
   public void showAbout(ActionEvent event) throws IOException {
      Stage primaryStage = new Stage();
      Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("othello/view/about.fxml"));
      Scene scene = new Scene(root);
      scene.getStylesheets().add("othello/view/about.css");

      primaryStage.setScene(scene);
      primaryStage.setResizable(false);
      primaryStage.sizeToScene();
      primaryStage.setTitle("About");
      primaryStage.show();
   }

   //Metodo per visualizzare il background del team da menu item in formato HTML
   @FXML
   public void showBackground(ActionEvent event) throws IOException {
      Stage primaryStage = new Stage();
      Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("othello/view/teamBackground.fxml"));
      Scene scene = new Scene(root);
      scene.getStylesheets().add("othello/view/teamBackground.css");

      primaryStage.setScene(scene);
      primaryStage.setResizable(false);
      primaryStage.sizeToScene();
      primaryStage.setTitle("Team Background");
      primaryStage.show();
   }
}

My Board FXML

<VBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="460.0" prefWidth="600.0" styleClass="root" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="othello.controller.BoardController">
   <children>
      <MenuBar>
        <menus>
          <Menu mnemonicParsing="false" text="Game">
            <items>
                  <MenuItem mnemonicParsing="false" onAction="#cleanStart" text="New Game" />
                  <MenuItem mnemonicParsing="false" onAction="#restartGame" text="Restart" />
                  <SeparatorMenuItem mnemonicParsing="false" />
                  <MenuItem mnemonicParsing="false" onAction="#helpMe" text="Next move" />
                  <SeparatorMenuItem mnemonicParsing="false" />
                  <Menu mnemonicParsing="false" text="Music">
                    <items>
                      <MenuItem mnemonicParsing="false" onAction="#audioY" text="On" />
                        <MenuItem mnemonicParsing="false" onAction="#audioN" text="Off" />
                    </items>
                  </Menu>
                  <SeparatorMenuItem mnemonicParsing="false" />
              <MenuItem mnemonicParsing="false" onAction="#exitProgram" text="Quit" />
            </items>
          </Menu>
          <Menu mnemonicParsing="false" text="Help">
            <items>
              <MenuItem mnemonicParsing="false" onAction="#playRules2" text="How to play" />
              <MenuItem mnemonicParsing="false" onAction="#showAbout" text="About" />
            </items>
          </Menu>
          <Menu mnemonicParsing="false" text="Project">
               <items>
                  <MenuItem mnemonicParsing="false" onAction="#showBackground" text="Team Background" />
               </items>
          </Menu>
            <Menu mnemonicParsing="false" text="Log Match">
               <items>
                  <MenuItem mnemonicParsing="false" onAction="#openLog" text="Last 10 matches.." />
               </items>
            </Menu>
        </menus>
      </MenuBar>
      <SplitPane dividerPositions="0.6833333333333333" styleClass="root">
        <items>
          <AnchorPane maxWidth="410.0" minHeight="0.0" minWidth="-Infinity">
               <children>
                  <GridPane fx:id="myGrid" alignment="CENTER" gridLinesVisible="true" layoutX="3.0" layoutY="5.0" prefHeight="400.0" prefWidth="400.0" styleClass="scacchiera">
                    <columnConstraints>
                      <ColumnConstraints halignment="CENTER" hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                      <ColumnConstraints halignment="CENTER" hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                        <ColumnConstraints halignment="CENTER" hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                        <ColumnConstraints halignment="CENTER" hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                        <ColumnConstraints halignment="CENTER" hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                        <ColumnConstraints halignment="CENTER" hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                        <ColumnConstraints halignment="CENTER" hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                        <ColumnConstraints halignment="CENTER" hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                    </columnConstraints>
                    <rowConstraints>
                      <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                      <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                      <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                        <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                        <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                        <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                        <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                        <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                    </rowConstraints>
                     <padding>
                        <Insets bottom="2.0" left="2.0" right="2.0" top="2.0" />
                     </padding>
                     <children>
                        <ImageView fx:id="imageView00" fitHeight="48.0" fitWidth="48.0" onMouseClicked="#handleOnMouseClicked" pickOnBounds="true" preserveRatio="true" />
                        <ImageView fx:id="imageView01" fitHeight="48.0" fitWidth="48.0" onMouseClicked="#handleOnMouseClicked" pickOnBounds="true" preserveRatio="true" GridPane.columnIndex="1" />
                        <ImageView fx:id="imageView02" fitHeight="48.0" fitWidth="48.0" onMouseClicked="#handleOnMouseClicked" pickOnBounds="true" preserveRatio="true" GridPane.columnIndex="2" />

                     </children>
                  </GridPane>
               </children>
            </AnchorPane>
          <AnchorPane SplitPane.resizableWithParent="false">
               <padding>
                  <Insets bottom="4.0" left="4.0" right="4.0" top="4.0" />
               </padding>
               <children>
                  <Button layoutX="115.0" layoutY="369.0" mnemonicParsing="false" onAction="#restartGame" text="Restart" textAlignment="CENTER" />
                  <TextField fx:id="txt_field_p1" layoutX="9.0" layoutY="36.0" promptText="Insert name.." />
                  <TextField fx:id="txt_field_p2" layoutX="9.0" layoutY="90.0" promptText="Insert name..." />
                  <Label layoutX="7.0" layoutY="14.0" styleClass="text" text="Player 1 name:" textFill="WHITE" />
                  <Label layoutX="7.0" layoutY="70.0" styleClass="text" text="Player 2 name:" textFill="WHITE" />
                  <Label layoutX="43.0" layoutY="151.0" styleClass="text" text="Choose color:" textFill="WHITE" />
                  <Label layoutX="10.0" layoutY="171.0" styleClass="text" text="P1" textFill="WHITE" />
                  <Label layoutX="100.0" layoutY="172.0" styleClass="text" text="P2" textFill="WHITE" />
                  <RadioButton fx:id="rd_p1_black" layoutX="46.0" layoutY="193.0" mnemonicParsing="false" onAction="#chooseColor" prefHeight="0.0" prefWidth="0.0">
                     <toggleGroup>
                        <ToggleGroup fx:id="group_p1" />
                     </toggleGroup></RadioButton>
                  <RadioButton fx:id="rd_p2_black" layoutX="134.0" layoutY="193.0" mnemonicParsing="false" onAction="#chooseColor" prefHeight="0.0" prefWidth="0.0">
                     <toggleGroup>
                        <ToggleGroup fx:id="group_p2" />
                     </toggleGroup></RadioButton>
                  <ImageView fitHeight="35.0" fitWidth="32.0" layoutX="11.0" layoutY="186.0" pickOnBounds="true" preserveRatio="true">
                     <image>
                        <Image url="@../images/black.png" />
                     </image>
                  </ImageView>
                  <ImageView fitHeight="35.0" fitWidth="32.0" layoutX="11.0" layoutY="218.0" pickOnBounds="true" preserveRatio="true">
                     <image>
                        <Image url="@../images/white.png" />
                     </image>
                  </ImageView>
                  <RadioButton fx:id="rd_p1_white" layoutX="46.0" layoutY="225.0" mnemonicParsing="false" onAction="#chooseColor" prefHeight="0.0" prefWidth="0.0" toggleGroup="$group_p1" />
                  <ImageView fitHeight="35.0" fitWidth="32.0" layoutX="101.0" layoutY="186.0" pickOnBounds="true" preserveRatio="true">
                     <image>
                        <Image url="@../images/black.png" />
                     </image>
                  </ImageView>
                  <ImageView fitHeight="35.0" fitWidth="32.0" layoutX="101.0" layoutY="218.0" pickOnBounds="true" preserveRatio="true">
                     <image>
                        <Image url="@../images/white.png" />
                     </image>
                  </ImageView>
                  <RadioButton fx:id="rd_p2_white" layoutX="134.0" layoutY="225.0" mnemonicParsing="false" onAction="#chooseColor" prefHeight="0.0" prefWidth="0.0" toggleGroup="$group_p2" />
                  <Label layoutX="67.0" layoutY="270.0" styleClass="text" text="Score:" textFill="WHITE" />
                  <Label layoutX="10.0" layoutY="298.0" styleClass="text" text="P1" textFill="WHITE" />
                  <Label layoutX="100.0" layoutY="298.0" styleClass="text" text="P2" textFill="WHITE" />
                  <Label fx:id="p1_totScore" layoutX="33.0" layoutY="312.0" styleClass="text" text="0" textFill="#d9dd96">
                     <font>
                        <Font size="36.0" />
                     </font>
                  </Label>
                  <Label fx:id="p2_totScore" layoutX="126.0" layoutY="313.0" styleClass="text" text="0" textFill="#d9dd96">
                     <font>
                        <Font size="36.0" />
                     </font>
                  </Label>
                  <Button fx:id="btn_start" layoutX="61.0" layoutY="369.0" mnemonicParsing="false" onAction="#newGame" text="Start" textAlignment="CENTER" />
                  <Button fx:id="btn_pass" layoutX="11.0" layoutY="369.0" mnemonicParsing="false" onAction="#passRound" text="Pass" />
               </children>
            </AnchorPane>
        </items>
         <padding>
            <Insets bottom="4.0" />
         </padding>
      </SplitPane>
      <GridPane prefHeight="20.0">
        <columnConstraints>
          <ColumnConstraints hgrow="SOMETIMES" maxWidth="20.0" minWidth="0.0" prefWidth="0.0" />
            <ColumnConstraints hgrow="SOMETIMES" maxWidth="30.0" minWidth="0.0" prefWidth="30.0" />
          <ColumnConstraints hgrow="SOMETIMES" minWidth="2.0" prefWidth="2.0" />
            <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
            <ColumnConstraints halignment="RIGHT" hgrow="SOMETIMES" maxWidth="30.0" minWidth="0.0" prefWidth="30.0" />
            <ColumnConstraints hgrow="SOMETIMES" maxWidth="20.0" minWidth="0.0" prefWidth="0.0" />
        </columnConstraints>
        <rowConstraints>
          <RowConstraints />
            <RowConstraints />
            <RowConstraints />
        </rowConstraints>
         <children>
            <ImageView fx:id="imgCount_p1" fitHeight="15.0" fitWidth="15.0" pickOnBounds="true" preserveRatio="true" GridPane.halignment="LEFT" GridPane.rowIndex="1" GridPane.valignment="CENTER">
               <image>
                  <Image url="@../images/black.png" />
               </image>
            </ImageView>
            <ImageView fx:id="imgCount_p2" fitHeight="15.0" fitWidth="15.0" pickOnBounds="true" preserveRatio="true" GridPane.columnIndex="5" GridPane.halignment="RIGHT" GridPane.rowIndex="1" GridPane.valignment="CENTER">
               <image>
                  <Image url="@../images/white.png" />
               </image>
            </ImageView>
            <Label fx:id="label_count_p1" styleClass="text" text="0" textFill="WHITE" GridPane.columnIndex="1" GridPane.rowIndex="1">
               <font>
                  <Font name="System Bold" size="16.0" />
               </font>
            </Label>
            <Label fx:id="label_count_p2" alignment="CENTER_RIGHT" styleClass="text" text="0" textFill="WHITE" GridPane.columnIndex="4" GridPane.rowIndex="1">
               <font>
                  <Font name="System Bold" size="16.0" />
               </font>
            </Label>
            <Label fx:id="label_output" alignment="CENTER_RIGHT" contentDisplay="CENTER" maxWidth="-Infinity" minWidth="-Infinity" prefWidth="300.0" styleClass="text" text="Black starts moving" textAlignment="CENTER" textFill="#f6ff00" GridPane.columnIndex="2" GridPane.rowIndex="1">
               <font>
                  <Font name="System Bold" size="14.0" />
               </font>
            </Label>
            <Label fx:id="label_coord" alignment="CENTER_RIGHT" contentDisplay="CENTER" maxWidth="-Infinity" minWidth="-Infinity" prefHeight="18.0" prefWidth="228.0" styleClass="text" text="0:0" textAlignment="CENTER" textFill="#f6ff00" GridPane.columnIndex="3" GridPane.rowIndex="1">
               <font>
                  <Font name="System Bold" size="14.0" />
               </font>
            </Label>
         </children>
      </GridPane>
      <ImageView fitHeight="48.0" fitWidth="48.0" pickOnBounds="true" preserveRatio="true" />
   </children>
</VBox>

Here the error stack trace updated today! When I click the start button (to change scene), this error comes out.

Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
    at com.sun.javafx.scene.control.skin.MenuBarSkin.lambda$new$383(MenuBarSkin.java:304)
    at javafx.event.WeakEventHandler.handle(WeakEventHandler.java:79)
    at com.sun.javafx.event.CompositeEventHandler$WeakEventFilterRecord.handleCapturingEvent(CompositeEventHandler.java:312)
    at com.sun.javafx.event.CompositeEventHandler.dispatchCapturingEvent(CompositeEventHandler.java:98)
    at com.sun.javafx.event.EventHandlerManager.dispatchCapturingEvent(EventHandlerManager.java:223)
    at com.sun.javafx.event.EventHandlerManager.dispatchCapturingEvent(EventHandlerManager.java:180)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchCapturingEvent(CompositeEventDispatcher.java:43)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:52)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$ClickGenerator.postProcess(Scene.java:3470)
    at javafx.scene.Scene$ClickGenerator.access$8100(Scene.java:3398)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3766)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at com.sun.glass.ui.gtk.GtkApplication.lambda$null$49(GtkApplication.java:139)
    at java.lang.Thread.run(Thread.java:745)
1

There are 1 best solutions below

1
On BEST ANSWER

I don't think this has anything to do with FXML because I've got an application that throws the same exception but I'm not using any FXML. My application started doing this when I added functionality to change to a new Scene on the primary Stage for my application. The root Parent for these stages is a BorderPane with a MenuBar node set as the "top" node.

The workaround that I did to prevent this (and it seems to work well) is to clear out the "top" node from the BorderPane in the previous Scene before setting the new scene. I added a method that gets called right before setting the new scene (requires saving reference to the 'stage' provided by Application.start(Stage)):

    private void clearBorderPane() {
        if ((stage != null) && (stage.getRoot() instanceof BorderPane)) {
             BorderPane pane = (BorderPane)stage.getRoot();
             pane.setTop(null);
        }
    }

It seems disassociating the menu from the parent layout is what does it, but I could be mistaken.

Of course this applies only to mine and similar applications with a MenuBar in the top of a BorderPane. For other types of root panes it might be worth removing the MenuBar from the list of child nodes of whatever type of Pane it getting used as the root for the scene.