Setting background image by javafx code (not css)

前端 未结 2 2040
攒了一身酷
攒了一身酷 2021-01-04 22:23

I\'m trying to set an image as the background using this code:

root.setStyle(\"-fx-background-image: url(\'splash.jpg\'); 
               -fx-background-posi         


        
相关标签:
2条回答
  • 2021-01-04 23:11

    If you really don't want to use CSS or the setStyle() method, you can use the following:

    // new Image(url)
    Image image = new Image(CurrentClass.class.getResource("/path/to/package/bg.jpg"));
    // new BackgroundSize(width, height, widthAsPercentage, heightAsPercentage, contain, cover)
    BackgroundSize backgroundSize = new BackgroundSize(100, 100, true, true, true, false);
    // new BackgroundImage(image, repeatX, repeatY, position, size)
    BackgroundImage backgroundImage = new BackgroundImage(image, BackgroundRepeat.REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, backgroundSize);
    // new Background(images...)
    Background background = new Background(backgroundImage);
    

    You can find detailed documentation on BackgroundImage here.

    (Sorry for replying to this old question.)

    0 讨论(0)
  • 2021-01-04 23:24

    Try next:

    String image = JavaFXApplication9.class.getResource("splash.jpg").toExternalForm();
    root.setStyle("-fx-background-image: url('" + image + "'); " +
               "-fx-background-position: center center; " +
               "-fx-background-repeat: stretch;");
    
    0 讨论(0)
提交回复
热议问题