java.lang.NullPointerException它工作,但错误。试图找到错误

时间:2017-09-01 11:41:33

标签: java javafx nullpointerexception fxml fxmlloader

当我点击"开始按钮"时出现错误,它会为我加载一个新的fxml我会玩它,它工作正常,但控制台告诉我这个错误..我无法理解如何解决它。

我的FXML :(仅查看startGame,这给我一些问题)

    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();
   }
}

我的董事会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>

今天错误堆栈跟踪已更新!当我单击开始按钮(更改场景)时,会出现此错误。

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 个答案:

答案 0 :(得分:1)

我认为这与FXML没有任何关系,因为我有一个引发相同异常的应用程序,但是我没有使用任何FXML。当我在应用程序的主阶段上添加了更改为新的场景的功能时,我的应用程序开始执行此操作。这些阶段的根 Parent BorderPane ,其中将 MenuBar 节点设置为“顶部”节点。

我要防止这种情况的解决方法(似乎工作得很好)是在之前的 Scene 中从 BorderPane 中清除“顶部”节点设置新场景。我添加了一个在设置新场景之前就被调用的方法(需要保存对由 Application.start(Stage) 提供的“舞台”的引用):

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

看起来菜单与父级布局无关,但是我可能会误会。

当然,这仅适用于在 BorderPane 顶部带有 MenuBar 的矿山和类似应用程序。对于其他类型的根窗格,可能有必要从其用作场景根的 Pane 类型的子节点列表中删除 MenuBar >