【问题标题】:JavaFX: How do I set a Background Image in code?JavaFX:如何在代码中设置背景图像?
【发布时间】:2014-10-29 14:10:27
【问题描述】:

我有一个必须高度可定制的控件,这意味着能够使用图像作为控件背景。为此,我需要知道如何在代码中将 CSS 样式设置为指向用户指定的图像。

我有以下内容(不起作用,我收到有关“未知协议:c”的警告(我什至不知道那是什么意思)):

BG = //The CSS String
    "-fx-background-position : 50% 50%;\n" +
    "-fx-background-repeat : no-repeat;\n" +
    "-fx-background-size : contain;\n" +
    "-fx-background-image : url(\"" + GS.bgImage.getAbsolutePath() + "\");\n";

BG += "-fx-border-width : " + GS.borderWidth + ";\n" //For adding the Border
    + "-fx-border-color : " + GS.borderColor.toString();

this.setStyle(BG);

GS 是我构造的一个类,控件从该类中读取信息以了解如何使自己看起来像。 GS.bgImage 是背景图像控件试图用作它的背景。所以......我在这里做错了什么?我不应该使用.getAbsolutePath() 吗?是别的吗?

【问题讨论】:

    标签: java css javafx


    【解决方案1】:

    好的,事实证明尝试使用 File.getPath() 或 File.getAbsolutePath() 来做是问题所在。结果是让它在你需要使用 File.toURI().toURL() 的代码中工作。

    所以正确的方法是:

    BG = //The CSS String, you need to wrap with a Try/Catch to capture a MalformedURLException, but I'm too lazy to do that here...
        "-fx-background-position : 50% 50%;\n" +
        "-fx-background-repeat : no-repeat;\n" +
        "-fx-background-size : contain;\n" +
        "-fx-background-image : url(\"" + GS.bgImage.toURI().toURL + "\");\n";
    
    BG += "-fx-border-width : " + GS.borderWidth + ";\n" //For adding the Border
        + "-fx-border-color : " + GS.borderColor.toString();
    

    【讨论】:

      猜你喜欢
      • 2014-11-06
      • 2012-04-08
      • 2016-10-03
      • 1970-01-01
      • 2020-05-05
      • 2012-04-02
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      相关资源
      最近更新 更多