2017-08-10 71 views
-2

我有一个FXML表示,其中我有我的FX:ID定义为contentPane的我让我的控制器内的空指针给FX后:身份证,仍然错误仍然存​​在

<center> 
      <Pane fx:id="ContentPane" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" /> 
     </center> 

虽然主应用程序,我有

public class Home_pageController extends Application { 

    @FXML 
    private Pane ContentPane; 

    /** 
    * Initializes the controller class. 
    */ 
    /** 
    * Initializes the controller class. 
    */ 
    @Override 
    public void start(Stage stage) throws Exception { 
     Parent root = FXMLLoader.load(getClass().getResource("home_page.fxml"));   
     Scene scene = new Scene(root); 
     stage.setTitle("Some scene");  
     stage.setScene(scene);   
     stage.show(); 
     MyGrid(); 
    } 
    public static void main(String[] args) { 
     launch(args); 
    } 
    public void MyGrid() throws IOException {   
     GridPane root = new GridPane(); 
     Label test = new Label("Test"); 
     root.add(test,0,0); 
     ContentPane.getChildren().clear(); 
     ContentPane.getChildren().add(root);   
    } 
    } 

我得到下面的错误

java.lang.NullPointerException 
    at controllers.Home_pageController.MyGrid(Home_pageController.java:70) 
    at controllers.Home_pageController.start(Home_pageController.java:62) 
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863) 
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326) 
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295) 
    at java.security.AccessController.doPrivileged(Native Method) 
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294) 
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95) 
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) 
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191) 
    at java.lang.Thread.run(Thread.java:745) 
+1

你从哪里调用'MyGrid()'?你可以发布其余的控制器代码,特别是你声明和注释'ContentPane'的地方。请更新您的代码以使用[正确命名约定(https://en.wikipedia.org/wiki/Naming_convention_(编程)#Java):它是非常难读它,如果你不遵循标准的命名方案。还要指出哪一行是抛出异常的行。 –

+0

@James_D,做检查更新的代码请。谢谢 –

+0

'ContentPane'(sic)只会在控制器中初始化,它不会在调用'launch()'时创建的'Application'子类的实例中初始化。 –

回答

2

如果fx:controller一个ttribute在FXML指定,FXMLLoader使用指定为属性值的类的构造器来构造一个新的实例控制器的

控制器的现有实例不会自动重复使用。

这就是为什么启动的应用程序实例的ContentPane字段永远不会被修改并仍然是null

+0

感谢的是,你有什么建议怎么办? –

+0

@DerinS与控制器进行通信,将必要的信息传递给它,请参阅https://stackoverflow.com/questions/14187963/passing-parameters-javafx-fxml顺便说一句:使用应用程序类作为控制器应避免恕我直言。 – fabian

相关问题