How to make a RadioButton look like regular Button

2020-02-11 05:22发布

问题:

I'm implementing a toolbox-like pane, so user can only pick one tool at a time, and I switched from Button to RadioButton for its behavior.

But I found that RadioButton uses its own skin with a dot, however I still want it to display like a normal Button. I'm a beginner with JavaFX and FXML, so anyone know how can I accomplish this?

回答1:

First Create a radio button, remove the radio-button style and then add the toggle-button style like

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

Hope that solves your problem



回答2:

Finally I went with another way around. You can extend ToggleButton so that it behaves like a RadioButton. This does not have the weird click effect of consuming mouse release.

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();
        }
    }
}

Then in FXML:

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

And it is done.



回答3:

Here is the style you can use to get rid of the dot

.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;
}

Documenting here; in case someone finds it useful.



回答4:

You can use ToggleButton and ToggleGroup, but you have to create an extension of ToggleGroup to keep the selected one selected. Here's an example.