代码之家  ›  专栏  ›  技术社区  ›  joepol

Javafx:ComboBoxTableCell-如何在一次单击中选择一个值?

  •  3
  • joepol  · 技术社区  · 7 年前

    我有一个带有ComboBoxTableCell的TableView,当使用默认实现时,用户必须单击 从组合框列表中选择值的时间。 我想当用户单击单元格时显示组合框列表。我的解决方案基于此: JavaFX editable ComboBox in a table view

    单元格确实进入编辑模式(调用startEdit()),但需要再次单击才能显示值列表,我缺少什么?

    table.addEventHandler(MouseEvent.MOUSE_CLICKED, (e) -> 
    {
     if (table.getEditingCell() == null) 
     {
         TablePosition focusedCellPos = table.getFocusModel().getFocusedCell();
         table.edit(focusedCellPos.getRow(), focusedCellPos.getTableColumn());
     }
    });
    

    谢谢

    2 回复  |  直到 7 年前
        1
  •  1
  •   kleopatra Aji kattacherry    5 年前

    有趣的问题-过了一段时间后又冒出来:)

    看起来OP的方法确实起到了作用(从fx11开始,其编辑周围的一些错误似乎得到了修复)-在组合单元格的帮助下:

    • 在tableView上的单击处理程序中开始编辑(从OP)
    • 扩展ComboBoxTableCell并重写其startEdit以打开下拉列表

    代码段:

    // set editable to see the combo
    table.setEditable(true);
    // keep approach by OP
    table.addEventHandler(MouseEvent.MOUSE_CLICKED, (e) -> {
        TablePosition<Person, ?> focusedCellPos = table.getFocusModel()
                .getFocusedCell();
        if (table.getEditingCell() == null) {
            table.edit(focusedCellPos.getRow(),
                    focusedCellPos.getTableColumn());
        }
    });
    // use modified standard combo cell shows its popup on startEdit
    firstName.setCellFactory(cb -> new ComboBoxTableCell<>(firstNames) {
    
        @Override
        public void startEdit() {
            super.startEdit();
            if (isEditing() && getGraphic() instanceof ComboBox) {
                // needs focus for proper working of esc/enter 
                getGraphic().requestFocus();
                ((ComboBox<?>) getGraphic()).show();
            }
        }
    
    });
    
        2
  •  0
  •   javafx_ing    5 年前

    也许不是这个问题最干净的解决方案,但我找到了一种解决方法,只需单击一次即可使ComboBoxTableCells下拉菜单:

    column.setCellFactory(new Callback<TableColumn<Person, String>, TableCell<Person, String>>() {
            @Override
            public TableCell<Person, String> call(TableColumn<Person, String> column) {
              ComboBoxTableCell cbtCell = new ComboBoxTableCell<>(cbValues);
              cbtCell.setOnMouseEntered(new EventHandler<Event>() {
                @Override
                public void handle(Event event) {
                  // Without a Person object, a combobox shouldn't open in that row
                  if (((Person)((TableRow)cbtCell.getParent()).getItem()) != null) {
                    Robot r = new Robot();
                    r.mouseClick(MouseButton.PRIMARY);
                    r.mouseClick(MouseButton.PRIMARY);
                  }
                }
              });
              return cbtCell;
            }
          });
    

    PS:我知道这个话题有点老了,但我最近也偶然发现了这个问题,在网上找不到任何有效的解决方案。我很难过,这不是最干净的解决办法,但至少它能完成它的工作