How to handle ListView item clicked action?

前端 未结 4 1904
再見小時候
再見小時候 2021-01-01 11:04

I have my JavaFX 2.0 application, where i need to make some action, after user clicked an item in ListView element. To construct user GUI i\'m using FXML, in which i have so

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-01 11:43

    You can also consume unwanted events on blank space.

    in call() of cell factory add:

    cell.setOnMousePressed((MouseEvent event) -> {
        if (cell.isEmpty()) {
           event.consume();
        }
    });
    

    This will disable click & dragStart too.

    Whole cellFactory example from my project:

    public static Callback, ListCell> getCellFactory() {
        return new Callback, ListCell>() {
    
            @Override
            public ListCell call(ListView param) {
                ListCell cell = new ListCell() {
    
                    @Override
                    protected void updateItem(BlockFactory item, boolean empty) {
                        super.updateItem(item, empty);
                        if (item != null) {
                            ImageView img = new ImageView(item.img);
                            Label label = new Label(item.desc);
                            HBox bar = new HBox(img, label);
                            bar.setSpacing(15);
                            bar.setAlignment(Pos.CENTER_LEFT);
                            setGraphic(bar);
                        }
                    }
                };
                cell.setOnMousePressed((MouseEvent event) -> {
                    if (cell.isEmpty()) {
                        event.consume();
                    }
                });
                return cell;
            }
        };
    }
    

提交回复
热议问题