代码之家  ›  专栏  ›  技术社区  ›  user1814946

JavaFX ToggleGroup在使用加速器时无法正常工作(RadioMenuItem)

  •  0
  • user1814946  · 技术社区  · 5 年前

    我正在使用带有多个RadioMenuItems的JavaFX菜单。这些项目位于切换组中,使用鼠标单击时可以正常工作。我需要这些项目的热键,并希望他们在下拉列表中显示,所以添加了加速器。这些也可以工作,但是如果再次使用已选定项目的热键组合,则该项目将被取消选择,在ToggleGroup中不保留任何选定选项。如果再次使用相同的组合,则所需的行为是保留选中的项。

    fxmlsnippit

    <Menu >
        <RadioMenuItem fx:id="item1" text="item 1" >
            <toggleGroup>
                <ToggleGroup fx:id="theToggleGroup" />
            </toggleGroup>
            <accelerator>
                <KeyCodeCombination alt="UP" code="d" control="DOWN" meta="UP" shift="UP" shortcut="UP" />
            </accelerator>
        </RadioMenuItem>
        <RadioMenuItem fx:id="item2" text="item 2" toggleGroup="$theToggleGroup">
            <accelerator>
                <KeyCodeCombination alt="UP" code="b" control="DOWN" meta="UP" shift="UP" shortcut="UP" />
            </accelerator>
        </RadioMenuItem>
    </Menu>
    

    JAVA

    theToggleGroup.selectedToggleProperty().addListener((observable, oldValue, newValue) -> doStuffBasedOnSelectedToggle(newValue));
    // null pointer on newValue when nothing is selected (should never happen in a ToggleGroup)
    

    onAction="#doStuffBasedOnSelectedToggle"
    

    在FXML中,但问题仍然是,如果您两次选择同一个,它将被取消选择。

    通过在热键“Ctrl+B”和“Ctrl+D”之间来回切换来模拟上述代码的这种行为,没有任何问题。“Ctrl+D”后跟“Ctrl+D”或“Ctrl+B”后跟“Ctrl+B”等出现问题。

    0 回复  |  直到 5 年前
        1
  •  1
  •   user1814946    5 年前

    item1.setOnAction(event -> {
        item1.setSelected(true);
        doStuffBasedOnSelectedToggle();
    }
    item2.setOnAction(event -> {
        item2.setSelected(true);
        doStuffBasedOnSelectedToggle();
    }
    

    使用此代码,它们可以适当地来回切换,并且如果两次选择相同的代码,它们将不会关闭。

    原始问题的根本原因似乎隐藏在Java库中

    com.sun.javafx.scene.control.ContralAcceleratorSupport.java -> doAcceleratorInstall(...) 
    

    此方法通过切换RadioMenuItems和CheckMenuItems来相同地处理它们。正确的行为应该是切换CheckMenuItem并将RadioMenuItem设置为true。