I want to change the styling of a button, most of the threads here and the articles on the internet show how to do it using Java code, which I don't see it as a real good solution, is there any way for example to set a button with some text and an image inside it all by using FXML only (no Css) ?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Solution using only fxml
As tarrsalah points out, css is the recommended way of doing this, though you can also do it in fxml if you prefer:
To get the above in SceneBuilder, drag an
ImageView
on top of aButton
and it will automatically be set as a graphic for the button. Then select theImageView
and type the url of the image into the ImageView's image field in the SceneBuilder properties pane.Open the above fxml in SceneBuilder to see the image below.
Alternate css attributes
Alternate css to the
-fx-background*
attributes.-fx-graphic
-fx-padding
-fx-content-display
-fx-graphic-text-gap
These are just different, not necessarily better for what you are trying to do. It is just a preference thing as to which to use. I find these settings easier to use than the
-fx-background*
settings. They are more restrictive, but the syntax and options are much easier for me to understand and their meanings map to the JavaDoc API for Labeled.A detailed description of the attributes is in the css reference guide.
Here's a example with a style setting the graphic embedded in the fxml, though it is always better to separate the style information out into a separate css stylesheet as in tarrsalah's sample.
Related solutions for adding images to buttons using only Java code
A couple of changes I made to the css example (ref. #btn { in comment #3):
This removed the button outline and left only the image. I was able to resize the button selector in the Scene Builder like an ImageView and see the picture change in realtime. I added a ToolTip to explain the image since there was no text and no button outline. I plan to use techniques explained elsewhere and alter the image when clicked to give more visual feedback that the image is a button.
Also note: I needed to specify the button id in the 'CSS Id' (Scene Builder) instead of the 'fx:id' to get them to be linked.
Adding these changes to what was explained above allowed me to accomplish my goal: have a button that looks only like the image (e.g. round shape in squarish button).
FXML is used just for designing the layout, for styling you can use css and reference it from your
FXML
file :To add an image to a
fx:id="btn"
button in yourcss
:This Github repository provide a complete running example: