Styling a JavaFX 2 button using FXML only - How to add an image to a button?

前端 未结 3 2136
臣服心动
臣服心动 2020-11-30 05:35

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 s

3条回答
  •  春和景丽
    2020-11-30 06:14

    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 a Button and it will automatically be set as a graphic for the button. Then select the ImageView 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.

    lovepotion


    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

    • JavaFX - create custom button with image
    • Add image to a button at a specific position JavaFX

提交回复
热议问题