在我的 FXML 中,我创建了一个网格 Pane 。现在我想添加动态元素(如按钮、文本字段)
通过 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();
}
}
最佳答案
您会得到一个空指针,因为您尝试在 stage.show() 之前执行操作,因此 fxml 尚未初始化。不要做脏事,把你的 greadPane.add 放在一个单独的 Controller 上
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 分配给此 Controller 。一切都会好的
关于JAVAFX 在 FXML Gridpane 中添加动态元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17261910/