How to remove the expand effect on button clicked

2020-07-22 10:12发布

问题:

How can I remove the small expand effect when I click on a JavaFX button? And also how can I make it work like an menu button (when I press it to remain in focused state untill I press another "menu" button). Is there a way to group nodes into the same focus?

回答1:

Three questions for the price of one ;-)

How can I remove the small expand effect when I click on a JavaFX button?

When you click the button it has focus, when it has focus, it is surrounded by the focus ring, which makes it slightly larger. This effect is triggered via css.

Default css is in caspian.css found in jfxrt.jar in your JavaFX runtime install. Relevant extract is here:

.button {
    -fx-skin: "com.sun.javafx.scene.control.skin.ButtonSkin";
    -fx-background-color: -fx-shadow-highlight-color, -fx-outer-border, -fx-inner-border, -fx-body-color;
    -fx-background-insets: 0 0 -1 0, 0, 1, 2;
    -fx-background-radius: 5, 5, 4, 3;

... }

.button:focused {
    -fx-color: -fx-focused-base;
    -fx-background-color: -fx-focus-color, -fx-outer-border, -fx-inner-border, -fx-body-color;
    -fx-background-insets: -1.4, 0, 1, 2;
    -fx-background-radius:  6.4, 5, 4, 3;
}

To remove the slight expansion effect, create your own stylesheet. In your stylesheet assign that to your scene and set the background insets and radius for the focused and unfocused button to the same values. Here is a tutorial on JavaFX CSS and the ever useful JavaFX CSS reference guide.

how can I make it work like an menu button (when I press it to remain in focused state untill I press another "menu" button).

I don't quite understand this question - that is the default behavior of a button. Maybe you are mixing focus and arm states and actually want a ToggleButton?

Is there a way to group nodes into the same focus?

Not built into the platform on the moment. You could write your own FocusModel class for a layout pane which remembers the last control in the pane which had focus and reassigns it focus again whenever the pane gets focus back or something like that. It would be custom code though. Concepts you would need to use are the focus property of nodes, the node requestFocus api (sometimes with a delay by executing in Platform.runLater to ensure that you override default focus processing) and the fact that (I think) the default focus order depends on the order of children within a Parent.



回答2:

Style your own favorite button if you don't like the default one. Otherwise explain the small expand effect with code or image.
Use Menu and MenuItems to make a menu.
Or use Toggle Button to group the buttons and to behave them like a menu.
By saying " to remain in focused state" I assume you meant the "selected/toggled state" instead of focused. Cause the button remains in focused state after clicking on it.