2016-02-19 58 views
0

嘗試從initialize()方法內訪問Button時,出現NullPointerException。嘗試訪問JavaFX按鈕時出現NullPointerException

我已經標記了下面這行會導致異常。

public class MyController implements Initializable { 
    @FXML 
    public Button connect; 

    public MyController() throws IOException { 
     FXMLLoader loader = new FXMLLoader(getClass().getResource("Layouts/ClientLayout.fxml")); 
     loader.setController(this); 
     Parent root = loader.load(); 
     Stage stage = new Stage(); 
     stage.setScene(new Scene(root, 460, 470)); 
     stage.show(); 
    } 

    @Override 
    public void initialize(URL location, ResourceBundle resources) { 
     connect.setOnAction(e -> { // this line causes the nullpointerexception 
      connect.setDisable(true); 
     }); 
    } 
} 
+0

你確定ClientLayout.fxml有fx:id的按鈕與連接? – subash

回答

0

您沒有初始化您的按鈕。檢查你的FXML。它應該包含正確的FX:ID:

<Button fx:id="connect" graphicTextGap="2.0" layoutX="716.0" layoutY="274.0" mnemonicParsing="false"> 

你也應該定義哪些做對在你FXML增加一個的OnAction方法的作用:

<Button fx:id="connect" graphicTextGap="2.0" layoutX="716.0" layoutY="274.0" mnemonicParsing="false" onAction="#handleConnectButtonAction"> 

,並在您的控制器,而不是把它在初始化的方法:

@FXML 
private void handleConnectButtonAction(ActionEvent event){ 
    connect.setDisable(true);   
} 
相關問題