2014-10-29 2266 views
0

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

我有以下的(没有工作,我得到一个关于“未知协议: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()?还有别的吗?

回答

0

好吧,事实证明试图用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();