如何阻止TextArea侦听快捷键组合作为KeyEvent?

时间:2018-09-29 19:29:00

标签: javafx shortcut keyevent

正如标题所述,如何停止在TextArea中将快捷键(加速器)用作键事件?我尝试了此处建议的方法,并进行了其他修改:TextArea ignore KeyEvent in JavaFX,但没有运气。

1 个答案:

答案 0 :(得分:0)

如果要在TextArea处于焦点时停止特定的加速器工作,只需为KEY_PRESSED事件添加事件过滤器。

public class AcceleratorFilter implements EventHandler<KeyEvent> {

  // blacklist of KeyCombinations
  private final Set<KeyCombination> combinations;

  public AcceleratorFilter(KeyCombination... combinations) {
    this.combinations = Set.of(combinations);
  }

  @Override
  public void handle(Event event) {
    if (combinations.stream().anyMatch(combo -> combo.match(event)) {
      event.consume();
    }
  }

}

TextArea area = new TextArea();
area.addEventFilter(KeyEvent.KEY_PRESSED, new AcceleratorFilter(
  KeyCombination.valueOf("shortcut+o"),
  KeyCombination.valueOf("shortcut+s") // etc...
));

如果您想不加选择地阻止所有在Scene注册的加速器,则可以查询Scene的加速器并在适当时使用KeyEvent

TextArea area = new TextArea();
area.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
  var scene = ((Node) event.getSource()).getScene();
  // #getAccelerators() = ObservableMap<KeyCombination, Runnable>
  var combos = scene.getAccelerators().keySet();
  if (combos.stream().anyMatch(combo -> combo.match(event)) {
    event.consume();
  }
});

如果您不小心,后一个选项可能会导致问题。例如,如果Button中有默认的Scene,则上述事件过滤器可能会干扰ENTER键。另外,此选项不一定会停止shortcut+cshortcut+v等操作,因为这些快捷方式是在TextInputControl而非Scene中注册的。