首页 文章

JavaFX从ObservableList填充TableView

提问于
浏览
2

我正在尝试使用ObservableList中的数据填充TableView . 我以前做过这个,但由于某种原因我现在无法让它工作 . 我没有得到任何例外或任何东西,但它只是不添加任何东西到表 .

this问题类似,但我发现了由JPA引起的另一个问题,因此提到的 Modification 的构造函数从未被执行过 . 相反,JPA可以分配值 .

这是我的代码 - 我剪断了与问题无关的代码:

FXML

<TableView fx:id="tblModifications" layoutX="14.0" layoutY="14.0" prefHeight="545.0" prefWidth="512.0">
    <columns>
        <TableColumn prefWidth="75.0" text="%itemNumber" fx:id="colModArt"/>
        <TableColumn prefWidth="75.0" text="%name" fx:id="colModName"/>
        <TableColumn prefWidth="75.0" text="%amount" fx:id="colModAmount" />
    </columns>
</TableView>

Main.java

public class Main extends Application implements Initializable {
    private TableView<Modification> tblModifications;
    private TableColumn<ObservableList<Modification>, String> colModArt;
    private TableColumn<ObservableList<Modification>, String> colModName;
    private TableColumn<ObservableList<Modification>, Integer> colModAmount;

    @Override
    public void initialize(URL arg0, ResourceBundle arg1){
        colModArt.setCellValueFactory(new PropertyValueFactory<>("barcodeProperty"));
        colModName.setCellValueFactory(new PropertyValueFactory<>("nameProperty"));
        colModAmount.setCellValueFactory(new PropertyValueFactory<>("amountProperty"));

        admin = Administration.getInstance();

        tblModifications.setItems(admin.observableModifications); // This list is populated with correct data, I tested.
    }

    @Override
    public void start(Stage primaryStage) throws Exception{
        resources = ResourceBundle.getBundle("strings", new Locale("NL"));
        Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("main.fxml"), resources);
        primaryStage.setTitle(resources.getString("title"));
        primaryStage.setScene(new Scene(root, 1280, 1024));
        primaryStage.show();
    }
}

Modification.java

public class Modification {
    public SimpleStringProperty barcodeProperty;
    public SimpleStringProperty nameProperty;
    public SimpleIntegerProperty amountProperty;
    private int id;
    private Seller seller;
    private Product product;
    private int amount;
    private Boolean accepted;

    public Modification(int id, Seller seller, Product product, int amount) {
        this.id = id;
        this.seller = seller;
        this.product = product;
        this.amount = amount;
        this.accepted = false;

        barcodeProperty.set(String.valueOf(product.getBarcode()));
        nameProperty.set(product.getName());
        amountProperty.set(amount);
    }
}

任何帮助解决这个问题将不胜感激!

1 回答

  • 1

    看来这个问题部分是由JPA引起的 .

    首先,我在 PropertyValueFactory 中使用了不正确的字段名称 . 我不得不从它们中移除 Property 部分,因为显然这是自动添加的(反射?)

    其次,JPA实现从未执行 Modification 构造函数,因此 SimpleStringProperty 永远不会得到它的值 . 我通过为这些值编写自己的getter解决了这个问题: getProductNamegetProductBarcode

相关问题