【问题标题】:Setting background image by javafx code (not css)通过 javafx 代码(不是 css)设置背景图像
【发布时间】:2012-04-08 17:18:48
【问题描述】:

我正在尝试使用此代码将图像设置为背景:

root.setStyle("-fx-background-image: url('splash.jpg'); 
               -fx-background-position: center center; 
               -fx-background-repeat: stretch;");

但它不起作用。如果我用 CSS 设置它,它可以完美地工作:

root.setId("pane");
primaryStage.getScene().getStylesheets().add(JavaFXApplication9.class.getResource("style.css").toExternalForm());

和 CSS:

#pane{
   -fx-background-image: url('splash.jpg');
   -fx-background-repeat: stretch;   
   -fx-background-position: center center;
}

我所有的文件(主类、CSS 和图像)都放在同一个包中。

那么,如何使用代码设置背景图片呢?或者,如何从应用程序代码中覆盖(替换)有关 CSS 中某些元素的背景图像的行?谢谢!

【问题讨论】:

    标签: javafx-2


    【解决方案1】:

    尝试下一个:

    String image = JavaFXApplication9.class.getResource("splash.jpg").toExternalForm();
    root.setStyle("-fx-background-image: url('" + image + "'); " +
               "-fx-background-position: center center; " +
               "-fx-background-repeat: stretch;");
    

    【讨论】:

      【解决方案2】:

      如果你真的不想使用 CSS 或 setStyle() 方法,你可以使用以下:

      // 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);
      

      你可以在BackgroundImagehere找到详细的文档。

      (抱歉回答这个老问题。)

      【讨论】:

      • 这只是为我制作了一个空白 VBox:pastebin.com/s71vYfDM
      • @JoshDiamond 在我看来,给 new Image(...) 的构造函数的 url 在您的代码中可能不正确。您是否尝试过使用 getResource(...) 代替?
      猜你喜欢
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-05
      • 2016-09-01
      • 2019-03-24
      • 1970-01-01
      相关资源
      最近更新 更多