单击其他控件时 JavaFX CheckBox 更改大小

JavaFX CheckBox changes size when clicking other control

当我单击复选框时,它会改变大小,然后在选中它后,单击 GUI 上不是复选框的另一个控件,复选框的大小会改变大约 1 像素。我怎样才能让它停止?我附上了一张 gif 来说明我的意思。

.check-box {
    -fx-background-radius: 20px;
    -fx-background-color: linear-gradient(to right, #030045, #002869);
    -fx-text-fill: #ffffff;
    -fx-padding: 6px 10px;
}

.check-box > .box {
    -fx-background-radius: 8px;
    -fx-background-color: white;
    -fx-padding: 3px;
}

.check-box:selected > .box > .mark,
.check-box:indeterminate  > .box > .mark {
    -fx-background-color: #030045;
}

编辑:我创建了一个没有容器(例如 HBox)的新空白项目并添加了相同的样式表,但我仍然得到相同的错误,这意味着它必须与 CSS 相关,而与其他无关处理其他控件或布局的大小。

这是由于节点的可遍历性,当 CheckBox 处于焦点时它将突出显示节点(由于 CSS 而您看不到)。

下面是一些示例代码,您可以在其中打开和关闭 CheckBox 的可遍历特性。(我在样式表中使用上面提供的相同 CSS)

下面是 JavaDoc,它告诉您有关 setFocusTraversable 函数的更多信息

public class Main extends Application {

    @Override
    public void start(Stage stage) {
        VBox vBox = new VBox();
        Scene scene = new Scene(vBox);
        scene.getStylesheets().add(String.valueOf(getClass().getClassLoader().getResource("StyleSheetTest.css")));

        CheckBox checkBox = new CheckBox("Test CheckBox");
        checkBox.setFocusTraversable(false);

        Button button = new Button("Other Control");

        ToggleButton toggleButton = new ToggleButton("FocusTraversable:False");
        toggleButton.setOnAction(event -> {
            if(toggleButton.isSelected()){
                toggleButton.setText("FocusTraversable:True");
                checkBox.setFocusTraversable(true);
            } else {
                toggleButton.setText("FocusTraversable:False");
                checkBox.setFocusTraversable(false);
            }
        });

        vBox.getChildren().addAll(checkBox, button, toggleButton);
        vBox.setAlignment(Pos.CENTER);
        stage.setScene(scene);
        stage.show();
    }
}

Java文档:

setFocusTraversable

public final void setFocusTraversable(boolean value)

Sets the value of the property focusTraversable.

Property description: Specifies whether this Node should be a part of focus traversal cycle. When this property is true focus can be moved to this Node and from this Node using regular focus traversal keys. On a desktop such keys are usually TAB for moving focus forward and SHIFT+TAB for moving focus backward. When a Scene is created, the system gives focus to a Node whose focusTraversable variable is true and that is eligible to receive the focus, unless the focus had been set explicitly via a call to requestFocus().

Default value: false

来源:https://docs.oracle.com/javase/8/javafx/api/javafx/scene/Node.html#setFocusTraversable-boolean-