2016-08-14 190 views
0

當我調用變量empName時,我的應用程序拋出了NullPointer異常。JavaFX拋出的空指針異常

  ResultSet result = stmnt.executeQuery("select FirstName, LastName from emp_info where EmployeeID " 
        + "= '" + empID + "'"); 

//   while(result.next()){ 
//    empName.setText("result.getString(1)); 
//   } 
      empName.setText("asdf"); 
      rootLayout.setCenter(controlData); 

      connection.close(); 
     } 

    } 

它應該能夠運行良好,因爲我初始化文本變量,像這樣:

@FXML 
public Text empName; 

此外,當我使用scenebuilder,它有時會顯示FX:ID empName但是當我退出的出它並重新打開它並不顯示它。我認爲這是問題所在。我的XML文件是:

<AnchorPane prefHeight="300.0" prefWidth="500.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="studentempsignin.MainPage_Controller"> 
    <children> 
     <BorderPane prefHeight="300.0" prefWidth="500.0"> 
     <center> 
      <Text fx:id="empName" strokeType="OUTSIDE" strokeWidth="0.0" text="Text" BorderPane.alignment="CENTER" /> 
     </center> 
     </BorderPane> 
    </children> 
</AnchorPane> 

我得到的例外是:

SEVERE: null 
java.lang.NullPointerException 
    at studentempsignin.MainPage_Controller.signingIn(MainPage_Controller.java:190) 
    at studentempsignin.SignIn_Controller.lambda$0(SignIn_Controller.java:66) 
    at studentempsignin.SignIn_Controller$$Lambda$143/575703892.handle(Unknown Source) 
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86) 
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238) 
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191) 
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59) 

編輯:

方法empIDAccess被稱爲當我點擊簽到按鈕:

signInBtn.setOnAction((e) -> { 
      try { 
       //used dbaseDriver...idk why 
//    DBaseDriver connect = new DBaseDriver("jdbc:mysql://localhost:3306/AUStudentEmployees", 
//      "kheneahm", "kennygoham"); 
       String empID = empIDField.getText(); 
       MainPage_Controller empIDAccess = new MainPage_Controller(); 
       empIDAccess.signingIn(empID, invalidID, signInBtn); 
      } catch (Exception ex) { 
       Logger.getLogger(SignIn_Controller.class.getName()).log(Level.SEVERE, null, ex); 
      } 

     }); 
+0

確實有一些未初始化的東西。 – Danieboy

+0

請顯示更多的上下文。顯然你是從另一個控制器調用一個控制器的方法? –

+0

你也知道爲什麼scenebuilder有時不會顯示id字段嗎? –

回答

0

您正在創建一個新的控制器實例。當您加載FXML文件時,FXMLLoader創建一個控制器實例並在該實例中初始化@FXML -annotated字段。這些字段不會在您創建的新實例中初始化(即使它們是,它們也不會引用UI中顯示的相同對象)。您需要登錄get a reference to the controller that is created when you load the FXML