How to make a RadioButton look like regular Button in JavaFX

后端 未结 4 2152
耶瑟儿~
耶瑟儿~ 2020-12-18 07:04

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.

<
相关标签:
4条回答
  • 2020-12-18 07:27

    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.

    0 讨论(0)
  • 2020-12-18 07:33

    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.

    0 讨论(0)
  • 2020-12-18 07:37

    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

    0 讨论(0)
  • 2020-12-18 07:47

    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.

    0 讨论(0)
提交回复
热议问题