【问题标题】:how to overwrite system default keyboard shortcuts like Ctrl+C, Ctrl+V by using Javafx KeyCombination?如何使用 Javafx KeyCombination 覆盖系统默认键盘快捷键,如 Ctrl+C、Ctrl+V?
【发布时间】:2020-07-19 04:19:33
【问题描述】:

在实现撤消/重做机制时,我编写了下面的代码来将粘贴操作添加到我自己的撤消堆栈中。如果我单击菜单项,它正在执行事件处理代码,但如果我使用快捷键 Ctrl+V,我的事件处理程序不会执行。

更多信息参见下面的代码。

        MenuItem paste = new MenuItem("Paste");

        KeyCombination pasteKeyCombination = new KeyCodeCombination(KeyCode.V,KeyCombination.CONTROL_DOWN);

        paste.setAccelerator(pasteKeyCombination);

        paste.setOnAction(event -> {
            System.out.println("Ctrl+V triggered.");
            if(clipboard.hasString()){
                String pastedText = clipboard.getString();
                InsertCommand insertCommand = new InsertCommand(textArea.getCaretPosition(),pastedText,textArea);
                insertCommand.execute();
                UndoRedo.insertIntoUndoStack(insertCommand);
            }
        });

如果我使用不同的 KeyCode,例如 Ctrl+J,它可以正常工作,但不能用于 Ctrl+V。

注意:当我使用 Ctrl+V 时,它似乎直接从系统剪贴板粘贴数据,而不是执行我的代码。

谁能提出这个问题的解决方案?请解释为什么它可以使用 Ctrl+J 而为什么不能使用 Ctrl+V?

所有剪切、复制、粘贴快捷方式都存在问题。

【问题讨论】:

  • 关于导致问题的原因,TextArea 的行为添加了实现剪切/复制/粘贴/撤消/重做/等的各种处理程序。这些处理程序消耗事件。这意味着这些事件永远不会到达现场,这在这种情况下是一个问题,因为只有在匹配的事件冒泡到现场时才会调用加速器。
  • @Slaw 感谢您的评论。在这种情况下,我们如何在 textarea 上覆盖此行为?
  • 所有默认键绑定都存储在TextInputControlBindings 类中。 TextInputControlBehavior 及其子类 TextAreaBehavior 使用这些绑定。不幸的是,扩展 TextAreaBehavior 以更改键绑定似乎不是一个选项(在 JDK-8 上检查),因为 TextAreaSkin 不允许您指定自定义行为。

标签: java javafx java-8


【解决方案1】:

由于找不到合适的解决方案,我暂时尝试了一些解决方法,方法是添加 onKeyPress 事件处理程序,它正在执行处理程序实现,即使是 Ctrl+C、Ctrl+V 等也是如此。

        MenuItem paste = new MenuItem("Paste");
        this.textArea.addEventHandler(KeyEvent.KEY_PRESSED,event -> {
            if(event.isControlDown()&& event.getCode()==KeyCode.V){
                System.out.println("Ctrl+V is triggered");
                if(clipboard.hasString()){
                    String pastedText = clipboard.getString();
                    InsertCommand insertCommand = new InsertCommand(textArea.getCaretPosition(),pastedText,textArea);
                    insertCommand.execute();
                    UndoRedo.insertIntoUndoStack(insertCommand);
                }
            }
        });

注意:仍然不清楚为什么它不能与 KeyCombination 一起使用。如果有人有答案,请发布。

【讨论】:

    【解决方案2】:

    问题是TextArea(它是一个内部类)的行为添加了许多EventHandlers 来处理各种用户生成的事件(例如按键)。这包括用于剪切、复制、粘贴、撤消、重做、全选等的常用快捷方式。然后这些处理程序consume 停止所述事件传播的事件。由于菜单项加速器仅在事件回升到Scene 时才起作用,因此TextArea 行为所消耗的事件意味着您的菜单项不会触发。

    一种解决方法是在TextArea 上使用自定义EventDispatcher 来过滤掉与多个键组合中的任何一个匹配的任何键事件。允许所有其他事件正常进行,而其余的行为保持不变。这是通过阻止事件到达TextArea 并让事件进入事件传播的冒泡阶段来实现的,最终让事件冒泡支持场景图。最后一点就是为什么需要使用EventDispatcher 而不是事件过滤器的原因;在事件过滤器中使用事件将阻止事件到达TextArea,但不会让它在场景图中冒泡。

    这是一个例子:

    import java.util.Set;
    import javafx.application.Application;
    import javafx.event.Event;
    import javafx.event.EventDispatchChain;
    import javafx.event.EventDispatcher;
    import javafx.scene.Scene;
    import javafx.scene.control.Menu;
    import javafx.scene.control.MenuBar;
    import javafx.scene.control.MenuItem;
    import javafx.scene.control.TextArea;
    import javafx.scene.input.KeyCombination;
    import javafx.scene.input.KeyEvent;
    import javafx.scene.layout.Priority;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    
    public class Main extends Application {
    
      @Override
      public void start(Stage primaryStage) {
        MenuItem cutItem = new MenuItem("Cut");
        cutItem.setAccelerator(KeyCombination.valueOf("shortcut+x"));
        cutItem.setOnAction(e -> System.out.println("CUT"));
    
        MenuItem copyItem = new MenuItem("Copy");
        copyItem.setAccelerator(KeyCombination.valueOf("shortcut+c"));
        copyItem.setOnAction(e -> System.out.println("COPY"));
    
        MenuItem pasteItem = new MenuItem("Paste");
        pasteItem.setAccelerator(KeyCombination.valueOf("shortcut+v"));
        pasteItem.setOnAction(e -> System.out.println("PASTE"));
    
        TextArea area = new TextArea();
        area.setEventDispatcher(
            new FilteringEventDispatcher(
                area.getEventDispatcher(),
                cutItem.getAccelerator(),
                copyItem.getAccelerator(),
                pasteItem.getAccelerator()));
    
        VBox root = new VBox(new MenuBar(new Menu("Edit", null, cutItem, copyItem, pasteItem)), area);
        VBox.setVgrow(area, Priority.ALWAYS);
    
        primaryStage.setScene(new Scene(root, 600, 400));
        primaryStage.show();
      }
    
      private static class FilteringEventDispatcher implements EventDispatcher {
    
        private final EventDispatcher delegate;
        private final Set<KeyCombination> blacklistedCombos;
    
        public FilteringEventDispatcher(EventDispatcher delegate, KeyCombination... blacklistedCombos) {
          this.delegate = delegate;
          // Set.of was added in Java 9
          this.blacklistedCombos = Set.of(blacklistedCombos);
        }
    
        @Override
        public Event dispatchEvent(Event event, EventDispatchChain tail) {
          if (!(event instanceof KeyEvent) || isPermitted((KeyEvent) event)) {
            return delegate.dispatchEvent(event, tail); // forward event to TextArea
          }
          return event; // skip TextArea and enter the bubbling phase
        }
    
        private boolean isPermitted(KeyEvent event) {
          return blacklistedCombos.stream().noneMatch(combo -> combo.match(event));
        }
      }
    }
    

    如有必要,您可以通过测试事件的 EventType 来更具体地过滤(例如,仅过滤 KEY_PRESSED 事件)。您还可以根据需要将组合列入白名单而不是将其列入黑名单。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-08
      • 1970-01-01
      • 2019-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多