2017-08-09 15 views
0

工作,我想提出一個圖像上的標籤,而代碼:相對URL不是JavaFX中

Label userPic = new label(); 

ImageView userImage = new ImageView(
          new Image("test/123/headPortrait.png",50.0,50.0,false,false)); 

userPic.setGraphic(userImage); 

但它不斷地拋出java.lang.IllegalArgumentException: Invalid URL or resource not found.

我已經試過file://headPortrait.pngfile://E:/eclipse/ClassSchedule/headPortrait.png(絕對URL)。這次編譯器沒有拋出任何異常,但圖像仍然不顯示,應用程序運行速度非常緩慢。

在我嘗試添加圖片到標籤之前,我所有的代碼都完美地工作。

+0

有效的URL是'E:/eclipse/ClassSchedule/headPortrait.png'或'/ test/123/headPortrait.png'而不是你寫的 – azro

+0

可能的重複[JavaFX 8圖像加載(找不到無效的URL或資源)](https://stackoverflow.com/questions/28489402/javafx-8-image-load-invalid-url-or-resource-not-found) –

回答

-1

將ImageView放入標籤並不是一件好事。我會建議你直接將ImageView添加到場景中。 要加載類路徑中的圖像將被使用ResourceStream做了最好的方式,

this.getClass().getResourceAsStream("/assets/headPortrait.png") 

爲例。在這種情況下,您的圖片必須位於名爲assets的文件夾中。 你的整個代碼看起來是這樣的:

ImageView imageView = new ImageView(new Image(this.getClass().getResourceAsStream("/assets/headPortrait.png"), 50, 50, false, true)); 

我會推薦給你的形象構造函數的最後布爾標誌設置爲true,因爲它增加了圖像的質量。

+1

我強烈支持使用[embedded-resource](https:/ /stackoverflow.com/tags/embedded-resource/info),但爲什麼不利用'Label'' Labeled'控件的'ContentDisplay'? – trashgod