gpt4 book ai didi

java - TableView getSelectedIndex 返回异常值

转载 作者:太空宇宙 更新时间:2023-11-04 13:32:01 27 4
gpt4 key购买 nike

我有一个在场景生成器中制作的 JavaFX 窗口,带有 2 个 Activity 按钮和一个存储商品项的 TableView。商品是一个由 2 个相同的类(产品和服务)实现的接口(interface)。相关代码:

@FXML
private TableView<Commodity> commoditiesTable;

commoditiesTable.setOnMouseClicked((MouseEvent event) -> {
int selectedIndex = commoditiesTable.getSelectionModel().getSelectedIndex();
commoditiesTable.getItems().stream().forEach((c) -> {
System.out.println(c.getName());
});
System.out.println(selectedIndex);
});

@FXML
//Button
private void setTableViewProducts() {
commoditiesTable.setItems(DataSupplier.getProducts());
System.out.println("Products");
}

@FXML
//Button
private void setTableViewServices() {
commoditiesTable.setItems(DataSupplier.getServices());
System.out.println("Services");
}

DataSupplier 在两种方法中都返回一个 ObservableList,其中包含 2 个元素,由 Id 和 name 字段组成。触发“setOnMouseClicked”按预期工作,直到通过其他类的按钮更新 TableView,此时

commoditiesTable.getSelectionModel().getSelectedIndex();

开始返回-1。

单击产品按钮并选择第一个元素,重复,然后再次单击服务和产品后,此代码片段的输出:

Products
product1
product2
0
Products
product1
product2
0
Services
service1
service2
-1
Products
product1
product2
-1

如果我选择除第一个元素以外的元素或在切换到产品之前从服务开始,行为是相同的。

最佳答案

生成了错误值,因为即使正确的元素在表中以视觉方式突出显示,commoditiesTable.getSelectionModel() 仍然指向旧的 ObservableList。在表格上调用 getSelectionModel().clearSelection() 后,getSelectedIndex() 返回正确的值。

关于java - TableView getSelectedIndex 返回异常值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32078648/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com