正如标题所述,如何停止在TextArea中将快捷键(加速器)用作键事件?我尝试了此处建议的方法,并进行了其他修改:TextArea ignore KeyEvent in JavaFX,但没有运气。
答案 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+c
,shortcut+v
等操作,因为这些快捷方式是在TextInputControl
而非Scene
中注册的。