如何覆盖已安装的行为映射?

时间:2016-02-02 14:25:05

标签: javafx-8 java-9

在java-9中,Skins将其置于公共范围内,而行为则处于黑暗状态 - 尽管如此,现在使用InputMap对所有输入绑定进行了相当大的改动。

CellBehaviorBase安装鼠标绑定,如:

InputMap.MouseMapping pressedMapping, releasedMapping;
addDefaultMapping(
    pressedMapping = new InputMap.MouseMapping(MouseEvent.MOUSE_PRESSED, this::mousePressed),
    releasedMapping = new InputMap.MouseMapping(MouseEvent.MOUSE_RELEASED, this::mouseReleased),
    new InputMap.MouseMapping(MouseEvent.MOUSE_DRAGGED, this::mouseDragged)
);

具体的XXSkin现在私下安装行为:

final private BehaviorBase behavior; 
public TableCellSkin(TableCell control) {
    super(control);
    behavior = new TableCellBehavior(control);
    .... 
}

要求是替换mousePressed行为(在jdk9上下文中)。我们的想法是反思地抓住超级领域,处理所有映射并安装自定义行为。出于某种原因,我不明白,旧的绑定仍然是活动的(虽然旧映射是空的!)并且在新绑定之前调用

下面是一个可以运行的可运行示例:只是实现了对mousePressed的映射,什么都不做,特别是调用super。要查看旧的绑定,我在CellBehaviorBase.mousePressed中设置一个条件调试断点(在Eclipse中):

System.out.println("mousePressed super");
new RuntimeException("whoIsCalling: " + getNode().getClass()).printStackTrace();
return false;

运行调试并单击进入任何单元格,然后输出为:

mousePressed super
java.lang.RuntimeException: whoIsCalling: class de.swingempire.fx.scene.control.cell.TableCellBehaviorReplace$PlainCustomTableCell
    at com.sun.javafx.scene.control.behavior.CellBehaviorBase.mousePressed(CellBehaviorBase.java:169)
    at com.sun.javafx.scene.control.inputmap.InputMap.handle(InputMap.java:274)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)

//... lots more of event dispatching

// until finally the output in my custom cell behavior

Feb. 02, 2016 3:14:02 NACHM. de.swingempire.fx.scene.control.cell.TableCellBehaviorReplace$PlainCustomTableCellBehavior mousePressed
INFORMATION: short-circuit super: Bulgarisch

我希望只看到最后一部分,即我的自定义行为的打印输出。感觉就像我在某种程度上从根本上断了 - 但不能指出它。想法?

可运行的代码(对不起它的长度,大多数是锅炉板):

public class TableCellBehaviorReplace extends Application {

    private final ObservableList<Locale> locales =
            FXCollections.observableArrayList(Locale.getAvailableLocales());

    private Parent getContent() {
        TableView<Locale> table = createLocaleTable();
        BorderPane content = new BorderPane(table);
        return content;
    }

    private TableView<Locale> createLocaleTable() {
        TableView<Locale> table = new TableView<>(locales);

        TableColumn<Locale, String> name = new TableColumn<>("Name");
        name.setCellValueFactory(new PropertyValueFactory<>("displayName"));
        name.setCellFactory(p -> new PlainCustomTableCell<>());

        TableColumn<Locale, String> lang = new TableColumn<>("Language");
        lang.setCellValueFactory(new PropertyValueFactory<>("displayLanguage"));
        lang.setCellFactory(p -> new PlainCustomTableCell<>());

        table.getColumns().addAll(name, lang);
        return table;
    }

    /**
     * Custom skin that installs custom Behavior. Note: this is dirty!
     * Access super's behavior, dispose to get rid off its handlers, install
     * custom behavior.
     */
    public static class PlainCustomTableCellSkin<S, T> extends TableCellSkin<S, T> {

        private BehaviorBase<?> replacedBehavior;
        public PlainCustomTableCellSkin(TableCell<S, T> control) {
            super(control);
            replaceBehavior();
        }

        private void replaceBehavior() {
            BehaviorBase<?> old = (BehaviorBase<?>) invokeGetField(TableCellSkin.class, this, "behavior");
            old.dispose();
            // at this point, InputMap mappings are empty:
            // System.out.println("old mappings: " + old.getInputMap().getMappings().size());
            replacedBehavior = new PlainCustomTableCellBehavior<>(getSkinnable());
        }

        @Override
        public void dispose() {
            replacedBehavior.dispose();
            super.dispose();
        }

    }

    /**
     * Custom behavior that's meant to override basic handlers. Here: short-circuit
     * mousePressed.
     */
    public static class PlainCustomTableCellBehavior<S, T> extends TableCellBehavior<S, T> {

        public PlainCustomTableCellBehavior(TableCell<S, T> control) {
            super(control);
        }

        @Override
        public void mousePressed(MouseEvent e) {
            if (true) {
                LOG.info("short-circuit super: " + getNode().getItem());
                return;
            }
            super.mousePressed(e);
        }

    }


    /**
     * C&P of default tableCell in TableColumn. Extended to install custom
     * skin.
     */
    public static class PlainCustomTableCell<S, T> extends TableCell<S, T> {

        public PlainCustomTableCell() {
        }

        @Override protected void updateItem(T item, boolean empty) {
            if (item == getItem()) return;

            super.updateItem(item, empty);

            if (item == null) {
                super.setText(null);
                super.setGraphic(null);
            } else if (item instanceof Node) {
                super.setText(null);
                super.setGraphic((Node)item);
            } else {
                super.setText(item.toString());
                super.setGraphic(null);
            }
        }

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

    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setScene(new Scene(getContent(), 400, 200));
        primaryStage.setTitle(FXUtils.version());
        primaryStage.show();
    }

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

    /**
     * Reflectively access super field.
     */
    public static Object invokeGetField(Class source, Object target, String name) {
        try {
            Field field = source.getDeclaredField(name);
            field.setAccessible(true);
            return field.get(target);
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    @SuppressWarnings("unused")
    private static final Logger LOG = Logger
            .getLogger(TableCellBehaviorReplace.class.getName());
}

修改

建议继承自抽象皮肤XXSkinBase而不是具体的XXSkin (然后你可以自由安装你想要的任何行为,dude :-)是非常合理的,应该是第一个选择。在特定情况下,XX是TableCell,即currently not possible,因为基类包含抽象包私有方法。此外,还有XX没有抽象基础(如f.i. ListCell)。

2 个答案:

答案 0 :(得分:1)

可能是InputMap中的错误:

深入研究我发现了一些与映射并行的内部簿记(eventTypeMappings)(这些是处理程序)。 InputMap正在监听映射中的更改并更新内部记录更改

mappings.addListener((ListChangeListener<Mapping<?>>) c -> {
    while (c.next()) {
        // TODO handle mapping removal
        if (c.wasRemoved()) {
            for (Mapping<?> mapping : c.getRemoved()) {
                removeMapping(mapping);
            }
        }

// removeMapping
private void removeMapping(Mapping<?> mapping) {
    // TODO
}

意味着永远不会清除内部结构,尤其是在behavior.dispose()中删除映射时。在查找eventHandlers时 - 通过inputMap.handle(e),请参阅问题中显示的调试堆栈跟踪 - 在内部簿记结构中找到旧处理程序。

早期实验的乐趣......; - )

最后,一个(非常肮脏,非常hacky!)解决方案是接管InputMap的工作并强制清理内部:

private void replaceBehavior() {
    BehaviorBase<?> old = (BehaviorBase<?>) invokeGetField(TableCellSkin.class, this, "behavior");
    old.dispose();
    cleanupInputMap(old.getInputMap());
    // at this point, InputMap mappings are empty:
    // System.out.println("old mappings: " + old.getInputMap().getMappings().size());
    replacedBehavior = new PlainCustomTableCellBehavior<>(getSkinnable());
}

/**
 * This is a hack around InputMap not cleaning up internals on removing mappings.
 * We remove MousePressed/MouseReleased/MouseDragged mappings from the internal map.
 * Beware: obviously this is dirty!
 * 
 * @param inputMap
 */
private void cleanupInputMap(InputMap<?> inputMap) {
    Map eventTypeMappings = (Map) invokeGetField(InputMap.class, inputMap, "eventTypeMappings");
    eventTypeMappings.remove(MouseEvent.MOUSE_PRESSED);
    eventTypeMappings.remove(MouseEvent.MOUSE_RELEASED);
    eventTypeMappings.remove(MouseEvent.MOUSE_DRAGGED);
}
BTW:以防任何人想知道wtf - 没有,当我编辑一个在java-9中停止工作的单元时,我在缺少commitOnFocusLost的周围。

答案 1 :(得分:0)

尝试从PlainCustomTableCellSkin继承抽象类TableCellSkinBase而不是TableCellSkin。 然后你可以调用超级构造函数,它将TableCellBehaviorBase对象作为附加参数。 然后你可以节省你的时间来替换它,直接用正确的方法初始化它。

只是为了更多的鼓励: TableCellSkin扩展了TableCellSkinBase TableCellBehavior扩展了TableCellBehaviorBase

还有一件事。您还需要在构造函数中调用super.init(tableCell)。 以TableCellSkin类为参考。