我正在尝试使用FXML创建一个简单的表。该表显示正常,但它不显示我的数据。这是我的主要计划。
public final class TableTest extends Application {
@Override
public void start(final Stage primaryStage) {
URL fxml = ClassLoader.getSystemClassLoader().getResource("Table.fxml");
FXMLLoader fxmlLoader = new FXMLLoader(fxml);
TableController tableController = new TableController();
fxmlLoader.setController(tableController);
try {
Pane rootPane = (Pane) fxmlLoader.load();
Scene scene = new Scene(rootPane);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(final String[] args) {
launch(args);
}
}
这是FXML。
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<BorderPane prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml">
<center>
<TableView fx:id="table">
<columns>
<TableColumn text="Column 1" fx:id="col1" minWidth="80.0" />
<TableColumn text="Column 2" fx:id="col2" minWidth="80.0" />
</columns>
</TableView>
</center>
</BorderPane>
这是控制器。
public final class TableController implements Initializable {
@FXML
private TableView<TableData> table;
@FXML
private TableColumn<TableData, String> col1;
@FXML
private TableColumn<TableData, String> col2;
@Override
public void initialize(final URL url, final ResourceBundle resourceBundle) {
final ObservableList<TableData> data = FXCollections.observableArrayList(
new TableData("C1R1", "C2R1"),
new TableData("C1R2", "C2R2")
);
table.setItems(data);
col1.setCellValueFactory(
new PropertyValueFactory<TableData, String>("col1Property"));
col2.setCellValueFactory(
new PropertyValueFactory<TableData, String>("col2Property"));
table.getColumns().setAll(col1, col2);
}
private final class TableData {
private StringProperty col1Property = new SimpleStringProperty();
private StringProperty col2Property = new SimpleStringProperty();
public TableData(final String col1, final String col2) {
col1Property.set(col1);
col2Property.set(col2);
}
public void setCol1(final String col1) {
col1Property.set(col1);
}
public String getCol1() {
return col1Property.get();
}
public StringProperty col1Property() {
return col1Property;
}
public void setCol2(final String col2) {
col2Property.set(col2);
}
public String getCol2() {
return col2Property.get();
}
public StringProperty col2Property() {
return col2Property;
}
}
}
谁能告诉我我错过了什么?
答案 0 :(得分:1)
你没有遗漏任何东西!事实上,你有太多的东西:
new PropertyValueFactory<TableData, String>("col1Property"));
构造函数参数应该是相关属性的变量名的字符串值,最后没有“Property” - 即,在此示例中只是“col1”。
另请参阅Can't fill Table with items with javafx以及PropertyValueFactory
的Javadoc。