确定单击了哪个JavaFX ListView项而不选择它 [英] Determine which JavaFX ListView item was clicked on without selecting it

查看:567
本文介绍了确定单击了哪个JavaFX ListView项而不选择它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的JavaFX应用程序有一个ListView,其中包含需要处理的项目。我有两个按钮,用户可以点击这两个按钮来处理列表中的下一个项目(即前进按钮),或者撤消列表中最后一个项目的处理(即后退按钮)。我不希望他们随意选择列表中的项目(他们应该只能使用这两个按钮移动)。但是,我希望他们能够右键单击项目以获得一些上下文菜单(例如,从列表中删除右键单击的项目)。

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).

推荐答案

使用单元工厂,以便您可以注册监听器 ListCell s,而不是 ListView

Use a cell factory, so that you can register the listener with the ListCells, 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 ;
});

(用你喜欢的任何类型替换 MyDataType 用于 ListView 。)

(Replace MyDataType with whatever type you are using for the ListView.)

这篇关于确定单击了哪个JavaFX ListView项而不选择它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆