如何在javafx中获取所有选定的行数据

时间:2015-08-15 22:14:48

标签: javafx-2 javafx-8 fxml

有问题!! 在javafx表视图中,我通过Shift + mouseClick或Clt + MouseClick应用了多个选定模式。通过这个

tblViewCurrentStore.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                tblViewCurrentStore.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
            }
        });

它在GUI上没问题,但问题是,如果我使用这段代码,它会给我最后一个选择单元格的值,

private void btnDeleteOnAction(ActionEvent event) {
        System.out.println(tblViewCurrentStore.getSelectionModel().getSelectedItem().getProductName().toString());
    }
  

Out Put SAMSUNG HDD

但是当我使用这段代码时,它会给出这个!

private void btnDeleteOnAction(ActionEvent event) {
        System.out.println(tblViewCurrentStore.getSelectionModel().getSelectedItems().toString());
    }

它给我这种类型的输出

[List.ListProduct@3a22ea22, List.ListProduct@6d99efa2, List.ListProduct@40fd0f67]

但我需要选择多行然后按删除它会显示所有选定的数据,如第一行。

听到我的GUI(有多个选择) enter image description here

2 个答案:

答案 0 :(得分:0)

您的代码存在多个问题:

  1. tblViewCurrentStore.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);只需要设置一次(因此它是一个setter)。在TableView初始化之后而不是每次点击都要这样做。

  2. SelectionModel#getSelectedItem()明确说明了它的作用:

  3.   

    返回当前选定的对象(位于选定的索引位置)。 如果选择了多个项目,这将返回getSelectedIndex()返回的索引中包含的对象(它始终是最近选择的项目的索引)。

    1. 最后SelectionModel#getSelectedItems返回所有选定的对象(如在Java Object中)。
    2. 所以如果你想要名字,你可以这样:

      List<String> names = tblViewCurrentStore.getSelectionModel().getSelectedItems().stream()
        .map(ListProduct::getProductName)
        .collect(Collectors.toList());
      

答案 1 :(得分:0)

您甚至可以使用此:

 ArrayList<YourModel> products = new ArrayList<>(table.getSelectionModel().getSelectedItems());
        for (YourModel model : models) {
            System.out.println(model);
        }

//或

 final List<YourModel> collect = table.getSelectionModel().getSelectedItems().stream().collect(Collectors.toList());
相关问题