JavaFX ListView & ContextMenu - getSelectedItem() 返回 null



我想在列表视图的行上使用上下文菜单项。在 listView 的 MOUSE_CLICKED 事件的事件处理程序中,getSelectionModel().getSelectedItem() 返回选定的项,这没关系。但是,当我处理上下文菜单项的onAction事件时,它返回null。但是,以图形方式选择该项目。有没有办法在第一次事件处理后"保留"选择?

以下是代码的相关部分:

    ListView<Text> nameList = new ListView<>();
    final ContextMenu cCm = new ContextMenu();
    MenuItem cItem = new MenuItem("someText");
    cCm.getItems().add(cItem);

nameList.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent e) {
            if (e.getButton() == MouseButton.SECONDARY) {
                    //its OK here:
                    System.out.println(nameList.getSelectionModel().getSelectedItem().getText());
                    cCm.show(nameList, e.getScreenX(), e.getScreenY());
            }
        }
    });
    cItem.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent e) {
            final Stage dialog = new Stage();
            dialog.initModality(Modality.WINDOW_MODAL);
            //nullPointerException on the following:
            Text t = new Text(nameList.getSelectionModel().getSelectedItem().getText());
            //showing dialog, etc.

我几乎创建了您所做的事情的精确副本,并且我的实现有效:

private void initRandomCardListView() {
    populateRandomList();
    final ContextMenu randomListContextMenu = new ContextMenu();
    MenuItem replaceCardMenuItem = new MenuItem("Replace");
    replaceCardMenuItem.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            replaceRandomCard();
        }
    });
    randomListContextMenu.getItems().add(replaceCardMenuItem);
    randomCardList.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            if (event.getButton().equals(MouseButton.SECONDARY)) {
                randomListContextMenu.show(randomCardList, event.getScreenX(), event.getScreenY());
            }
        }
    });
}
private void replaceRandomCard() {
    System.out.println("jobs done");
    System.out.println("card selected: " + randomCardList.selectionModelProperty().get().getSelectedItem().toString());
    System.out.println("card index: " + randomCardList.getSelectionModel().getSelectedIndex());
    System.out.println("card index: " + randomCardList.getSelectionModel().getSelectedItem().toString());
}

我没有任何空指针异常。总体而言,您的实现看起来不错。列表视图中的项目很可能有问题。

相关内容

  • 没有找到相关文章

最新更新