I would like to create a custom button, that has two states pressed or not, like a toggle button. I have got two images to do this (pressed and not pressed), so how can i create the button and display it with my images ? The button must take the size of the image.
I am not using FXML.
Thank you for helping.
I would like to create a custom button, that has two states pressed or
Share
There are a few different ways to accomplish this, I’ll outline my favourites.
This question asks about toggle behaviour so the answer focuses on that. If you don’t need the toggle behaviour, then just use a standard
Button, which can be styled the same as theToggleButtonreferenced in this answer.See also:
Use a ToggleButton and apply a custom style to it. I suggest this because your required control is "like a toggle button" but just looks different from the default toggle button styling.
My preferred method is to define a graphic for the button in css:
OR use the attached css to define a background image.
I prefer the -fx-graphic specification over the -fx-background-* specifications as the rules for styling background images are tricky and setting the background does not automatically size the button to the image, whereas setting the graphic does.
And some sample code:
NOTE: the
StackPaneBuilderused in this example has been deprecated and removed from JavaFX, replace that code withnew StackPane()and call methods on the resultant stack pane to set stack pane properties rather than using the builder.Some advantages of doing this are:
An alternate is to not use css and still use a ToggleButton, but set the image graphic in code:
The code based approach has the advantage that you don’t have to use css if you are unfamilar with it.
For best performance and ease of porting to unsigned applet and webstart sandboxes, bundle the images with your app and reference them by relative path urls rather than downloading them off the net.