2016-05-11 1 views
0

私はstartメソッドからFXML要素を使って(テキストの変更)いくつかのコードを書いています。しかし、コントローラクラスからメソッドを呼び出すと、NullPointerExceptionが発生することがわかりました。スレッドに関連する問題があることが判明しましたが、何かを得ることができました。私は、同じ問題を生成するいくつかのサンプルコードを含んでいます。startメソッドでFXML要素と対話するときにNullPointerExceptionを修正するにはどうすればよいですか?

メインクラス:

public class Main extends Application { 
    Controller C = new Controller(); 

    @Override 
    public void start(Stage stage) throws Exception { 
     Parent root = FXMLLoader.load(getClass().getResource("sample.fxml")); 
     Scene scene = new Scene(root, 300, 275); 
     stage.setTitle("FXML Welcome"); 
     stage.setScene(scene); 
     stage.show(); 
     C.handleSubmitButtonAction();//Error happens here. 
    } 

    public static void main(String[] args) { 
     launch(args); 
    } 
} 

コントローラクラス:

public class Controller{ 
    @FXML public Text actiontarget; 

    @FXML protected void handleSubmitButtonAction() { 
     actiontarget.setText("Sign in button pressed"); 
    } 
} 

FXMLコード:あなたは、コントローラクラスを指定した場合

<GridPane fx:id="GridPane" fx:controller="sample.Controller" xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10"> 
    <children> 
     <Text text="Welcome" GridPane.columnIndex="0" GridPane.rowIndex="0" GridPane.columnSpan="2"/> 
     <Label text="User Name:" GridPane.columnIndex="0" GridPane.rowIndex="1"/> 
     <TextField GridPane.columnIndex="1" GridPane.rowIndex="1"/> 
     <Label text="Password:" GridPane.columnIndex="0" GridPane.rowIndex="2"/> 
     <PasswordField fx:id="passwordField" GridPane.columnIndex="1" GridPane.rowIndex="2"/> 
     <HBox spacing="10" alignment="bottom_right" GridPane.columnIndex="1" GridPane.rowIndex="4"> 
      <Button text="Sign In" onAction="#handleSubmitButtonAction"/> 
     </HBox> 
     <Text fx:id="actiontarget" GridPane.columnIndex="1" GridPane.rowIndex="6"/> 
    </children> 
</GridPane> 

答えて

2

FXMLLoaderは、コントローラ自体のインスタンスを作成しますfxml内のfx:controller属性を使用します。

そのインスタンスへのアクセスを取得するには、FXMLLoaderインスタンスを作成し、FXMLをロードした後getController()を使用する必要があります。それ以外の場合は、値が挿入されているコントローラインスタンスは、自分で作成して保存するフィールドとは異なります。

FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml")) 
Parent root = loader.load(); 
C = loader.getController(); 
フィールドに格納します。
関連する問題