【发布时间】:2018-12-24 13:28:34
【问题描述】:
所以我正在学习如何使用 FXMl,但我遇到了另一个问题,即在运行时通过 fx:id 获取对对象的引用,我得到一个带有以下代码的空指针异常。
<TableView fx:id="productTable" layoutX="92.0" layoutY="319.0" prefHeight="97.0" prefWidth="363.0" GridPane.columnIndex="7" GridPane.columnSpan="5" GridPane.rowIndex="3" GridPane.rowSpan="2">
<columns>
<TableColumn prefWidth="98.0" text="Product ID" fx:id="productID"/>
<TableColumn prefWidth="110.0" text="Product Name" fx:id="productName"/>
<TableColumn prefWidth="131.0" text="Inventory Level" fx:id="productInventoryLevel"/>
<TableColumn prefWidth="128.0" text="Price per Unit" fx:id="productPrice"/>
</columns>
</TableView>
//Controller.java
@FXML private TableView<Product> productTable;
@FXML private TableColumn<Product, String> productID;
@FXML private TableColumn<Product, String> productPrice;
@FXML private TableColumn<Product, String> productName;
@FXML private TableColumn<Product, String> productInventoryLevel;
//Product properties declared the same as https://docs.oracle.com/javafx/2/ui_controls/table-view.htm#
private ObservableList<Product> productData = FXCollections.observableArrayList(
new Product(0, "Wheel", 100.99, 4, 0, 1),
new Product(1, "Seat", 50.0, 4, 0, 1));
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
System.out.println("Product ID factories");
productID.setCellValueFactory(new PropertyValueFactory<Product, String>("productID"));
productPrice.setCellValueFactory(new PropertyValueFactory<Product, String>("productPrice"));
productInventoryLevel.setCellValueFactory(new PropertyValueFactory<Product, String>("productInventoryLevel"));
productName.setCellValueFactory(new PropertyValueFactory<Product, String>("productName"));
productTable.setItems(productData);
System.out.println("Set items");
}
如您所见,我声明了@FXML 标记,然后是fx:id 的变量,在我的第一个打印语句之后,我在productID 上得到一个运行时空指针异常
编辑: 上面的代码当前运行没有错误,但只会填充我表的“productID”部分。
【问题讨论】:
-
在声明@FXML private TableView productTable 之后,如果我尝试从“productTable”调用任何方法,我也会得到一个空引用。
标签: java javafx nullpointerexception fxml fxmlloader