私は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>