单元格:如何通过键盘激活上下文菜单?

4

一个单元格上下文菜单无法通过键盘激活:其根本原因是contextMenuEvent被分派到了焦点节点——即包含表格,而不是单元格。Jonathan的错误评估概述了如何解决它:

这样做的“正确”方法可能是在TableView中覆盖buildEventDispatchChain并包括TableViewSkin(如果它实现了EventDispatcher),并将其继续转发到表行中的单元格。

尝试按照该路径进行操作(以下是ListView的示例,只是因为只需要实现一个级别的皮肤,而不是TableView的两个级别)。 它有效,但是单元格上下文菜单是由键盘弹出触发器激活的,但相对于表而不是相对于单元格定位。

问题:如何钩入分派链以使其相对于单元格位置?

可运行的代码示例:

package de.swingempire.fx.scene.control.et;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventDispatchChain;
import javafx.event.EventTarget;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Cell;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.MenuItem;
import javafx.scene.control.Skin;
import javafx.stage.Stage;

import com.sun.javafx.event.EventHandlerManager;
import com.sun.javafx.scene.control.skin.ListViewSkin;

/**
 * Activate cell contextMenu by keyboard, quick shot on ListView
 * @author Jeanette Winzenburg, Berlin
 */
public class ListViewETContextMenu extends Application {

    private Parent getContent() {
        ObservableList<String> data = FXCollections.observableArrayList("one", "two", "three");
//        ListView<String> listView = new ListView<>();
        ListViewC<String> listView = new ListViewC<>();
        listView.setItems(data);
        listView.setCellFactory(p -> new ListCellC<>(new ContextMenu(new MenuItem("item"))));
        return listView;
    }

    /**
         * ListViewSkin that implements EventTarget and 
         * hooks the focused cell into the event dispatch chain
         */
        private static class ListViewCSkin<T> extends ListViewSkin<T> implements EventTarget {
            private EventHandlerManager eventHandlerManager = new EventHandlerManager(this);

            @Override
            public EventDispatchChain buildEventDispatchChain(
                    EventDispatchChain tail) {
                int focused = getSkinnable().getFocusModel().getFocusedIndex();
                if (focused > - 1) {
                    Cell<?> cell = flow.getCell(focused);
                    tail = cell.buildEventDispatchChain(tail);
                }
               // returning the chain as is or prepend our
               // eventhandlermanager doesn't make a difference 
               // return tail;
               return tail.prepend(eventHandlerManager);
            }

            // boiler-plate constructor
            public ListViewCSkin(ListView<T> listView) {
                super(listView);
            }

        }

    /**
     * ListView that hooks its skin into the event dispatch chain.
     */
    private static class ListViewC<T> extends ListView<T> {

        @Override
        public EventDispatchChain buildEventDispatchChain(
                EventDispatchChain tail) {
            if (getSkin() instanceof EventTarget) {
                tail = ((EventTarget) getSkin()).buildEventDispatchChain(tail);
            }
            return super.buildEventDispatchChain(tail);
        }

        @Override
        protected Skin<?> createDefaultSkin() {
            return new ListViewCSkin<>(this);
        }

    }

    private static class ListCellC<T> extends ListCell<T> {

        public ListCellC(ContextMenu menu) {
            setContextMenu(menu);
        }

        // boiler-plate: copy of default implementation
        @Override 
        public void updateItem(T item, boolean empty) {
            super.updateItem(item, empty);

            if (empty) {
                setText(null);
                setGraphic(null);
            } else if (item instanceof Node) {
                setText(null);
                Node currentNode = getGraphic();
                Node newNode = (Node) item;
                if (currentNode == null || ! currentNode.equals(newNode)) {
                    setGraphic(newNode);
                }
            } else {
                /**
                 * This label is used if the item associated with this cell is to be
                 * represented as a String. While we will lazily instantiate it
                 * we never clear it, being more afraid of object churn than a minor
                 * "leak" (which will not become a "major" leak).
                 */
                setText(item == null ? "null" : item.toString());
                setGraphic(null);
            }
        }

    }
    @Override
    public void start(Stage primaryStage) throws Exception {
        Scene scene = new Scene(getContent());
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

在这里查看,http://stackoverflow.com/a/23420064/2855515 - brian
@brian 是的,我看到了 - 无论如何感谢你提供的参考 :-) 但是一个hack(另一个方法是跟踪contextMenu的显示属性并手动定位)不是我想要的 - 我想要钩入事件分派,使默认的显示/定位可以在客户端代码不需要进一步努力的情况下正常工作。 - kleopatra
1个回答

1
挖掘一些事实:
  • contextMenuEvent 在 scene.processMenuEvent(...) 中创建并触发
  • 对于键盘触发的事件,该方法计算相对于目标节点(即当前焦点所有者)中间某处的场景/屏幕坐标
  • 这些(场景/屏幕)绝对坐标无法更改:event.copyFor(...) 仅将它们映射到新的目标本地坐标

因此,任何自动化的希望都没有实现,我们必须重新计算位置。一个(暂定的)计算位置的地方是自定义 EventDispatcher。下面是一个原始的示例(缺少所有健全性检查,未经正式测试,可能会产生不良副作用!),它简单地将键盘触发的 contextMenuEvent 替换为新的 contextMenuEvent,然后再委托给注入的 EventDispatcher。客户端代码(例如 ListViewSkin)必须在 EventDispatchChain 前加入 targetCell。

/**
 * EventDispatcher that replaces a keyboard-triggered ContextMenuEvent by a 
 * newly created event that has screen coordinates relativ to the target cell.
 * 
 */
private static class ContextMenuEventDispatcher implements EventDispatcher {

    private EventDispatcher delegate;
    private Cell<?> targetCell;

    public ContextMenuEventDispatcher(EventDispatcher delegate) {
        this.delegate = delegate;
    }

    /**
     * Sets the target cell for the context menu.
     * @param cell
     */
    public void setTargetCell(Cell<?> cell) {
        this.targetCell = cell;
    }

    /**
     * Implemented to replace a keyboard-triggered contextMenuEvent before
     * letting the delegate dispatch it.
     * 
     */
    @Override
    public Event dispatchEvent(Event event, EventDispatchChain tail) {
        event = handleContextMenuEvent(event);
        return delegate.dispatchEvent(event, tail);
    }

    private Event handleContextMenuEvent(Event event) {
        if (!(event instanceof ContextMenuEvent) || targetCell == null) return event;
        ContextMenuEvent cme = (ContextMenuEvent) event;
        if (!cme.isKeyboardTrigger()) return event;
        final Bounds bounds = targetCell.localToScreen(
                targetCell.getBoundsInLocal());
        // calculate screen coordinates of contextMenu
        double x2 = bounds.getMinX() + bounds.getWidth() / 4;
        double y2 = bounds.getMinY() + bounds.getHeight() / 2;
        // instantiate a contextMenuEvent with the cell-related coordinates
        ContextMenuEvent toCell = new ContextMenuEvent(ContextMenuEvent.CONTEXT_MENU_REQUESTED, 
                0, 0, x2, y2, true, null);
        return toCell;
    }

}

// usage (f.i. in ListViewSkin)
/**
 * ListViewSkin that implements EventTarget and hooks the focused cell into
 * the event dispatch chain
 */
private static class ListViewCSkin<T> extends ListViewSkin<T> implements
        EventTarget {

    private ContextMenuEventDispatcher contextHandler = 
            new ContextMenuEventDispatcher(new EventHandlerManager(this));

    @Override
    public EventDispatchChain buildEventDispatchChain(
            EventDispatchChain tail) {
        int focused = getSkinnable().getFocusModel().getFocusedIndex();
        Cell cell = null;
        if (focused > -1) {
            cell = flow.getCell(focused);
            tail = cell.buildEventDispatchChain(tail);
        }
        contextHandler.setTargetCell(cell);
        // the handlerManager doesn't make a difference
        return tail.prepend(contextHandler);
    }

    // boiler-plate constructor
    public ListViewCSkin(ListView<T> listView) {
        super(listView);
    }

}

编辑

刚刚注意到一个微小的(?)问题,如果单元格没有自己的上下文菜单,则在单元格位置显示键盘激活的listView上的contextMenu。找不到不替换单元格未使用的事件的方法,可能仍然缺少事件分派中的一些明显的内容(?)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接