4

FXML でグリッドペインを作成しました。今、動的要素 (Like ボタン、テキストフィールド) を Java コード (FXML ではなく) で追加したいのですが、そうしようとするとエラーが発生します。助けてください。

私のFXML:

    <AnchorPane fx:controller="tableview.TableViewSample" id="AnchorPane" maxHeight="-     Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml">
  <children>
    <GridPane fx:id="greadpane" layoutX="0.0" layoutY="0.0" prefHeight="400.0" prefWidth="600.0">
      <columnConstraints>
        <ColumnConstraints fx:id="col0" hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
        <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
      </columnConstraints>
      <rowConstraints>
        <RowConstraints  fx:id="row0" minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
        <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
        <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
      </rowConstraints>
    </GridPane>
  </children>
    </AnchorPane> 

私のJavaコード:

    public class TableViewSample extends Application {

    @FXML private GridPane greadpane;
  public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws IOException {

        Pane myPane = (Pane)FXMLLoader.load(getClass().getResource
                ("tabviewexamlpe.fxml"));
        Scene scene = new Scene(myPane);
        stage.setTitle("Table View ");
        stage.setWidth(450);
        stage.setHeight(500);
        stage.setScene(scene);       

        final Label label = new Label("Address Book");
        label.setFont(new Font("Arial", 20));
        greadpane.add(label, 0, 0);
        stage.show();
}
}
4

2 に答える 2

13

stage.show() の前に操作を実行しようとすると null ポインターが発生するため、fxml はまだ初期化されていません。汚いことをしないで、別のコントローラーに grreadPane.add を配置してください

public class Controller implements Initializable {

    @FXML
    private GridPane greadpane;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        final Label label = new Label("Address Book");
        label.setFont(new Font("Arial", 20));
        greadpane.add(label, 0, 0);
    }
}

fxml をこのコントローラーに割り当てます。そしてそれは大丈夫です

于 2013-06-23T15:27:31.167 に答える
0

私は同じ問題に遭遇し、Agonist_ アドバイスを使用しましたが、gridPane を新しいコントローラーに分離する代わりに、stage.show() を待っているコードを実行するために 10ms 後に実行されるスレッドを作成しました。

public GameController(Game game) {
    game.addObserver(this);
    new Thread() {
        @Override
        public void run() {
            try {
                Thread.sleep(10);
                Platform.runLater(() -> {
                    game.startBeginnerRound();
                });
            } catch (InterruptedException ex) {
                Logger.getLogger(GameController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }.start();
}

この例では、observable が通知したとき、この場合は game.startBeginnerRound() が実行されたときに gridPane が更新されます。

于 2018-01-01T13:23:20.467 に答える