CTRL miming + Click multiple selection in ListView using Javafx

I am trying to find various ways to select multiple items in a ListView. The GUI will work on the touch screen, so I won’t be able to use CTRL + Click. By exploring the various previous posts, I was able to implement multiple selections by storing all the selected elements in an array, and then scrolling through it to get the final selection. The only problem with my code is that compared to CTRL + click, the selection is smooth, where when my code causes a tick flicker every time a new item is selected. So basically ListView clears all selections and then selects the right ones. Is there any way to make this transition smooth? Would it be easier to imitate a CTRL + click effect?

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);; } } } }); 
+5
source share
1 answer

You can handle the selection change when the user clicks on the ListCell themselves, instead of using standard event handling:

 @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 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(); } 
+5
source

Source: https://habr.com/ru/post/1260615/


All Articles