gpt4 book ai didi

JavaFX:禁用使用键盘控制 RadioButtons

转载 作者:行者123 更新时间:2023-12-03 23:05:41 27 4
gpt4 key购买 nike

我正在开始使用 JavaFX,并且我已经构建了一个小俄罗斯方 block 游戏。现在一切正常,但最后我决定添加一组单选按钮来选择难度 - 这里我遇到了一个问题:突然LEFT/RIGHT/UP/DOWN键只切换单选按钮,不控制游戏没有了。

为了处理游戏,我在场景中添加了一个按键事件监听器:

public void setKeyEventHandler() {
game.getScene().setOnKeyPressed(Field::handleKeyEvent);
}

private static void handleKeyEvent(KeyEvent event) {
// ... handle the event to move the figure
}

但正如我所说,自从我添加了单选按钮后,这不再执行。有没有办法禁止使用键盘键更改单选按钮,并使它们只能通过鼠标单击进行更改?我是否需要以某种方式从他们身上移开焦点?但是怎么做呢?

编辑:也许我应该补充一点,我只是使用 setOnAction() 函数来处理单选按钮的事件,例如:

classicModeButton.setOnAction((e) -> interestingMode = false); 
interestingModeButton.setOnAction((e) -> interestingMode = true);

最佳答案

第一种方法:

您可以将您的 RadioButton 设为 not focusable .

通过此更改,箭头键的默认按键监听器将不再更改 radio 的状态,因为它们不会获得焦点(即使被鼠标选中):

classicModeButton.setFocusTraversable(false);
interestingModeButton.setFocusTraversable(false);

这只有在你的 Scene 上没有其他可聚焦的 Nodes 时才有效,否则它们将处理关键事件在它可以被屏幕的事件处理程序处理之前。如果您有其他节点,请检查第二种方法。

示例片段:

// Init the variables
BooleanProperty interestingMode = new SimpleBooleanProperty(false);
RadioButton classicModeButton = new RadioButton("Classic");
RadioButton interestingModeButton = new RadioButton("Interesting");
ToggleGroup tg = new ToggleGroup();

classicModeButton.setToggleGroup(tg);
interestingModeButton.setToggleGroup(tg);
tg.selectToggle(classicModeButton);

// The radios should be not focusable
classicModeButton.setFocusTraversable(false);
interestingModeButton.setFocusTraversable(false);

// On toggle-change, the mode will be changed
interestingMode.bind(tg.selectedToggleProperty().isEqualTo(interestingModeButton));

// Just print the changes
tg.selectedToggleProperty().addListener((observable, oldValue, newValue) ->
System.out.println((newValue == interestingModeButton) ? "Hmm, interesting" : "Classic .. boring"));

scene.setOnKeyPressed(e ->
System.out.println((e.getCode().isArrowKey()) ? "Arrow pressed!" : "Other pressed, I don't care!"));

第二种方法:

您可以通过添加 event filter 来处理键事件而不是 Sceneconsume the event 的事件处理程序.这将捕获已经在捕获阶段(而不是冒泡阶段)的事件,因此该事件甚至不会到达您的(可聚焦的)Nodes:

scene.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
System.out.println((event.getCode().isArrowKey()) ? "Arrow pressed!" : "Other pressed, I don't care!");
event.consume();
});

这样,所有按键事件都会被捕获,当然也可以“让某些事件”通过。

可以找到有关如何传递事件的更多信息(例如)here .

关于JavaFX:禁用使用键盘控制 RadioButtons,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47840286/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com