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 get an exception when trying to swap elements in
- JFX scale image up and down to parent
- Dragging an undecorated Stage in JavaFX
- JavaFX sample issue
- How to change the font size in ListView in JavaFX?
相关文章
- Low quality icon in taskbar of a Stage. JavaFX
- Loading custom font using JavaFX 8 and css
- Javafx Platform.runLater never running
- JavaFX scrolling table update performance degrades
- Javafx select multiple rows
- Escape from a Number TextField in a JavaFX dialog
- How to merge cells in JavaFX Scene builder?
- Adding view with constructor arguments to a border
There are a few different ways to accomplish this, I'll outline my favourites.
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:
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.
You just need to create your own class inherited from parent. Place an ImageView on that, and on the mousedown and mouse up events just change the images of the ImageView.
A combination of previous 2 answers did the trick. Thanks. A new class which inherits from Button. Note: updateImages() should be called before showing the button.