如何使 RadioButton 看起来像 JavaFX 中的常规 Button

How to make a RadioButton look like regular Button in JavaFX

我正在实现一个类似工具箱的窗格,因此用户一次只能选择一个工具,我将其行为从 Button 切换到 RadioButton

但是我发现RadioButton使用了自己的带有点的皮肤,但是我仍然希望它像正常的Button一样显示。我是 JavaFX 和 FXML 的初学者,所以有人知道我该怎么做吗?

首先创建一个单选按钮,删除radio-button样式然后添加toggle-button样式如

RadioButton radioButton=new RadioButton("Radio");
radioButton.getStyleClass().remove("radio-button");
radioButton.getStyleClass().add("toggle-button");

希望能解决您的问题

您可以使用 ToggleButtonToggleGroup,但您必须创建 ToggleGroup 的扩展名才能使所选的保持选中状态。这是一个 example.

最后我换了个方法。您可以扩展 ToggleButton,使其表现得像 RadioButton。这没有消耗鼠标释放的怪异点击效果。

public class RadioToggleButton extends ToggleButton {

    // As in RadioButton.
    /**
     * Toggles the state of the radio button if and only if the RadioButton
     * has not already selected or is not part of a {@link ToggleGroup}.
     */
    @Override
    public void fire() {
        // we don't toggle from selected to not selected if part of a group
        if (getToggleGroup() == null || !isSelected()) {
            super.fire();
        }
    }
}

然后在 FXML 中:

<fx:define>
    <ToggleGroup fx:id="toolToggleGroup" />
</fx:define>
<RadioToggleButton toggleGroup="$toolToggleGroup" />
<RadioToggleButton toggleGroup="$toolToggleGroup" />

完成了。

这是您可以用来去掉圆点的样式

.radio-button > .radio {
  -fx-background-color: transparent;
  -fx-background-insets: 0;
  -fx-background-radius: 0px;
  -fx-padding: 0.0em; /* 4 8 4 8 */
}
.radio-button:selected > .radio > .dot {
  -fx-background-color: transparent;
}

在此处记录;万一有人觉得有用。