2016-03-25 13 views
0

startgameボタンとexitgameボタンを押しても、最初のシーンが表示され、プッシュしようとしているときにステージやクローズステージでシーンを変更したいNullPointerExceptionの場合、このボタンの1つがコンパイラを閉じます。JAVAFXでシーンを変更しているときにNullPointerExceptionが発生する

メインクラスと2つのfxmlファイルもありますが、ここに入れる必要はないと思います。アンカーペイン、プリミティブラベル、ボタンは2つしかありません。

package sample; 

import javafx.event.ActionEvent; 
import javafx.fxml.FXML; 
import javafx.fxml.FXMLLoader; 
import javafx.fxml.Initializable; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.layout.AnchorPane; 
import javafx.stage.Stage; 

import java.io.IOException; 
import java.net.URL; 
import java.util.ResourceBundle; 

public class Controller implements Initializable{ 

    private Stage stage = new Stage(); 

    private FXMLLoader loader = new FXMLLoader(); 

    private AnchorPane anchorPane = new AnchorPane(); 

    private Scene scene = new Scene(new AnchorPane()); 

    @FXML private Button startGameButton; 
    @FXML private Button endGameButton; 

    @FXML private Button buttonAnswer1; 
    @FXML private Button buttonAnswer2; 
    @FXML private Button buttonAnswer3; 
    @FXML private Button buttonAnswer4; 

    public void createScene(int typeOfScene) throws Exception 
    { 
     if (typeOfScene == 1) 
     { 
      loader = new FXMLLoader(getClass().getResource("/sample/sample.fxml")); 
      anchorPane = loader.load(); 

      scene = new Scene(anchorPane); 
      stage.setScene(scene); 
      stage.show(); 
     } 

     if (typeOfScene == 2) 
     { 
      scene = null; 

      loader = new FXMLLoader(getClass().getResource("/sample/episodesFXML.fxml")); 

      anchorPane = loader.load(); 

      scene = new Scene(anchorPane); 
      stage.setScene(scene); 
      stage.show(); 
     } 
    } 

    public void getPrimaryStage(Stage stage) throws Exception 
    { 
     this.stage = stage; 
     createScene(1); 
    } 

    @Override 
    public void initialize(URL location, ResourceBundle resources) { 
     startGameButton.setOnAction(event -> { 
      try { 
       createScene(2); 
      } catch (Exception e) 
      { 
       e.printStackTrace(); 
      } 
     }); 

     endGameButton.setOnAction(event -> { 
      stage.close(); 
     }); 
    } 
} 
+3

[Null Pointer Exceptionとは何ですか?それを修正するにはどうすればいいですか?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how -do-i-fix-it) – hotzst

+0

これは、あなたが追加の詳細を提供できない限り、確かにその質問の複製です...例えばその値は 'null'です... stacktraceは何を言っていますか? – fabian

+0

私は関数 'createScenes(2)'を呼び出すと、私は 'anchorPane = loader.load();'行に怒っていると私はプッシュボタンの終了ゲームは何も起こっていないが、私のステージを閉じる必要があります。 –

答えて

0

fxmlファイルがfx:controller属性でコントローラファイルにリンクされているような問題があります。コントローラでfxmlをロードしようとしましたが、それは処理/ロードされません。別のフォームを作成し、フォームを表示/非表示する方が簡単です。

+0

fxmlファイルからfx:controller属性を削除し、fxmlLoader.setController();を使用します。コントローラを動的に定義します。 – Tokazio

関連する問題