使用 Javafx 在 ListView 中模仿 CTRL+单击多选

Mimicking CTRL+Click Multiple Selection in ListView using Javafx

我正在尝试寻找在 ListView 中选择多个项目的不同方法。 GUI 将在触摸屏显示器上显示为 运行,因此我无法按 CTRL+单击。通过研究过去的各种帖子,我已经能够通过将所有选定项目保存在一个数组中然后循环遍历它以获得最终选择来实现多重选择。我的代码唯一的问题是,与 CTRL +click 相比,选择是顺利完成的,因为每次选择新项目时我的代码都会导致类型闪烁。所以基本上 listView 会清除所有选择,然后选择正确的选择。有没有办法让这个过渡顺利进行?模仿触摸来实现CTRL+点击效果会不会更简单?

selectedList = new int[totalTypes];//total number of item properties

for(int x=0; x<selectedList.length;x++){//0 = not selected, 1 = selected
    selectedList[x]=0;
}
testView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

    testView.setOnMouseClicked(new EventHandler<Event>(){
        @Override
        public void handle(Event event){
                if(selectedList[testView.getSelectionModel().getSelectedIndex()]==0){
                    selectedList[testView.getSelectionModel().getSelectedIndex()]=1;
                }
                else{
                    selectedList[testView.getSelectionModel().getSelectedIndex()]=0;
                }

                for(int x=0; x<selectedList.length;x++){
                    if(selectedList[x]==1){
                        testView.getSelectionModel().select(x); 
                    }
                    else{
                        testView.getSelectionModel().clearSelection(x);;
                    }
                }


        }

    });

您可以在用户单击 ListCell 时自行更改选择,而不是使用标准事件处理:

@Override
public void start(Stage primaryStage) {
    ListView<Integer> listView = new ListView<>();
    listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    listView.getItems().setAll(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    listView.addEventFilter(MouseEvent.MOUSE_PRESSED, evt -> {
        Node node = evt.getPickResult().getIntersectedNode();

        // go up from the target node until a list cell is found or it's clear
        // it was not a cell that was clicked
        while (node != null && node != listView && !(node instanceof ListCell)) {
            node = node.getParent();
        }

        // if is part of a cell or the cell,
        // handle event instead of using standard handling
        if (node instanceof ListCell) {
            // prevent further handling
            evt.consume();

            ListCell cell = (ListCell) node;
            ListView lv = cell.getListView();

            // focus the listview
            lv.requestFocus();

            if (!cell.isEmpty()) {
                // handle selection for non-empty cells
                int index = cell.getIndex();
                if (cell.isSelected()) {
                    lv.getSelectionModel().clearSelection(index);
                } else {
                    lv.getSelectionModel().select(index);
                }
            }
        }
    });

    Scene scene = new Scene(listView);

    primaryStage.setScene(scene);
    primaryStage.show();
}