2016-11-28 100 views
0

我必須爲學校項目創建一個應用程序。登錄後,您應該轉到儀表板。這有效,但是,當我嘗試將按鈕設置爲禁用時,它會引發NullPointerException。JavaFX NullPointerException其他類中的按鈕

在這個文件中,該階段(後登錄)改變:

public class ScreenController { 
    public void setScene(Stage stage, Parent root,Button button, String file){ 
     if(file == "dashboard"){ 
      stage = (Stage) button.getScene().getWindow(); 
      try { 
       root = FXMLLoader.load(getClass().getResource("Dashboard.fxml")); 
      } catch (IOException ex) { 
       System.out.println("IOException: "+ex); 
      } 
      Scene scene = new Scene(root); 
      stage.setTitle("Corendon - Dashboard"); 
      stage.setScene(scene); 

      stage.show(); 
      Dashboard dashboard = new Dashboard(); 
     } 
    } 
} 

而且在最後一行,按鈕應設置爲禁用...

Dashboard dashboard = new Dashboard(); 

..通過這個類:

public class Dashboard extends ScreenController { 
    @FXML public Button buttonDashboard1; 

    public Dashboard(){ 
     buttonDashboard1.setDisable(true); 
    } 
} 

但是,沒有工作,那麼將引發NullPointerException異常:

Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException 
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774) 
    at 
... 
Caused by: java.lang.NullPointerException 
    at fastenyourseatbelts.Dashboard.<init>(Dashboard.java:11) 
    at fastenyourseatbelts.ScreenController.setScene(ScreenController.java:33) 
    at fastenyourseatbelts.LoginController.buttonLogin(LoginController.java:74) 
    ... 59 more 

我想了幾個小時,但我沒有得到解決方案......有誰知道什麼是錯的,爲什麼?

回答

0

將代碼從控制器的構造函數移動到initialize。該方法由FXMLLoader調用,完成所有領域的注射後,因此應該有機會獲得buttonDashboard1實例:

public class Dashboard extends ScreenController { 
    @FXML public Button buttonDashboard1; 

    @FXML 
    private void initialize() { 
     buttonDashboard1.setDisable(true); 
    } 
} 

您還必須確保控制器無論是在FXML的根元素指定文件例如加載之前(與包的Dashboard類的取代packagename

<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="packagename.Dashboard"> 
    <children> 
     <Button text="click me" fx:id="buttonDashboard1"/> 
    </children> 
</VBox> 

或設置爲控制器爲FXML:

FXMLLoader loader = new FXMLLoader(getClass().getResource("Dashboard.fxml")); 
Dashboard dashboard = new Dashboard(); 
loader.setController(dashboard); 
root = loader.load(); 

(不要在這種情況下使用一個fx:controller屬性)

+0

太棒了,那就是訣竅!感謝您的幫助,fabian!我可以繼續這個項目:) –

相關問題