有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java通过在TableView(JavaFX)中选定的第二行第二列上的ENTER键显示上下文菜单

到目前为止,我只设法使contextMenu出现在 TableView一旦我用这个代码按下回车按钮contextMenu.show(tableView, Side.RIGHT, 0, 0);。但这样,contextmenu只能在静态位置弹出

一,。如何获取所选第2行第2列的x y位置

我希望contextmenu动态显示,即每当用户在选定行上按ENTER键时,contextmenu将显示在其第2列的选定行中:请查看下面的给定图片enter image description here

有这样的东西吗

contextMenu.show(tableView, x-SelectedRow2ndCol, y-SelectedRow2ndCol);

二,。Howto Contextmenu完全显示在可见区域中

例如,如果选定的行是TableView的最后一行,因此其位置位于屏幕的最低部分,则contextmenu仍将弹出最后一行上方的所有项目


共 (1) 个答案

  1. # 1 楼答案

    lookupAll可用于从TableView获取所有TableRow。找到所选的一个,并获取子TableCell,其中tableColumn与列匹配。这就得到了TableCell。使用^{}方法显示ContextMenu。这还负责将菜单保持在屏幕上

    从javadoc:

    If there is not enough room, the menu is moved to the opposite side and the offset is not applied.

    TableView上的键侦听器示例:

    ContextMenu contextMenu = ...
    
    TableColumn secondColumn = tableView.getColumns().get(1);
    
    tableView.setOnKeyReleased(evt -> {
        if (evt.getCode() == KeyCode.ENTER) {
            Set<Node> rows = tableView.lookupAll(".table-row-cell");
            Optional<Cell> n = rows.stream().map(r -> (Cell) r).filter(Cell::isSelected).findFirst();
    
            if (n.isPresent()) {
                Optional<Node> node = n.get().getChildrenUnmodifiable().stream()
                        .filter(c -> c instanceof TableCell && ((TableCell) c).getTableColumn() == secondColumn)
                        .findFirst();
    
                if (node.isPresent()) {
                    Node cell = node.get();
                    Bounds b = cell.getLayoutBounds();
                    contextMenu.show(cell, Side.BOTTOM, b.getWidth() / 2, b.getHeight() / -2);
                }
            }
        }
    });
    

    请注意,如果没有可见的选定表行,则此操作不起作用