在我的FXML中,我创建了一个gridpane。现在我要添加动态元素(如按钮,文本字段) 通过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();
}
}
答案 0 :(得分:12)
你得到一个空指针,因为你试图在stage.show()之前进行操作,所以fxml尚未初始化。不做脏事并将你的greadPane.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指定给此控制器。它会没事的
答案 1 :(得分:0)
我遇到了同样的问题并使用了Agonist_建议,但是我没有将gridPane分成新的控制器,而是创建了一个运行10ms以后执行等待stage.show()的代码的线程。
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通知它时更新gridPane,在这种情况下执行game.startBeginnerRound()。