2014-10-29 2267 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();