问题
My JavaFX application has a ListView that contains items that need to be processed. I have two buttons that the user can click to process the next item in the list (i.e. a "forward" button), or to undo the processing of the last item in the list (i.e. a "back" button). I don't want them to arbitrarily select items in the list (they should only be able to move around using those two buttons). However, I would like them to be able to right click on items to get some contextual menu (e.g. like deleting the right-clicked item from the list).
I have the following event filter added to disable selecting an item by clicking on it while still allowing the user to scroll through and look at all the items in the list.
instrList.addEventFilter(MouseEvent.MOUSE_PRESSED, event -> {
if (event.getButton() == MouseButton.SECONDARY)
System.out.println("right clicked... something");
event.consume();
});
What I am stuck on is determine which item on the list was clicked on so I can do something with it (again, e.g. remove it from the list).
回答1:
Use a cell factory, so that you can register the listener with the ListCell
s, instead of with the ListView
:
instrList.setCellFactory(lv -> {
ListCell<MyDataType> cell = new ListCell<MyDataType>() {
@Override
protected void updateItem(MyDataType item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
} else {
setText(item.toString());
}
}
};
cell.addEventFilter(MouseEvent.MOUSE_PRESSED, event -> {
if (event.getButton()== MouseButton.SECONDARY && (! cell.isEmpty())) {
MyDataType item = cell.getItem();
System.out.println("Right clicked "+item);
}
});
return cell ;
});
(Replace MyDataType
with whatever type you are using for the ListView
.)
来源:https://stackoverflow.com/questions/44979764/determine-which-javafx-listview-item-was-clicked-on-without-selecting-it