JavaFX CSS Button with Image - How to define the size of the image?

23,573

I had the same problem and found a workaround: instead of using -fx-image, I use -fx-background-image.

Note: I use an additional lib to use svg file in the following example.

CSS

#buttonWithImage { 
    -fx-background-image: url('myimage.svg');
    -fx-background-size: 30px;
    -fx-background-repeat: no-repeat;
    -fx-background-position: 90%;
}
Share:
23,573
javasuns
Author by

javasuns

Updated on July 30, 2022

Comments

  • javasuns
    javasuns almost 2 years

    I am trying to insert an image in a button using JavaFX CSS. Although, I can do it easily using the "-fx-graphic" tag, I cannot find a way to resize the image in whatever size I want.

    I can do this through the following FXML code, where I give 30 to my preferred width of image, but I would like to do this with pure CSS. Is there any way to do that?

    FXML

    <Button text="Press Me">
       <graphic>
          <ImageView fitWidth="30">
            <image>
              <Image url="myImage.png"/>
            </image>
          </ImageView>
       </graphic>
    </Button>
    

    CSS

    #buttonWithImage {          
        -fx-graphic: url("myImage.png");
    }
    
  • xeruf
    xeruf over 6 years
    most of the times -fx-background-position: center; is probably the preferred way, it was the piece missing for me in your answer
  • Cromax
    Cromax almost 6 years
    What library do you use for making url('*.svg') work with JavaFX? Apache Batik?
  • Cromax
    Cromax almost 6 years
    @pdem Thanks a lot!