2015-02-23 96 views
0

我想要的是我的GUI組件(導出爲jar文件,並被其他組件使用)可以通過使用存儲在jar文件旁邊的圖像文件夾中的圖像動態更改圖像。因此,在標籤中使用url不是一種選擇,因爲無論我如何嘗試,我的jxml文件在未包含在jar文件中時都找不到圖像資源。
因此我嘗試這樣的:在javafx中定義<Image/>標記

在我avatar.jxml文件

<ImageView> 
    <image> 
     <Image fx:id="myImage"/> 
    </image> 
</ImageView> 

在我的Java文件

public Image myImage = new Image("location of an image stored on computer"); 
URL location = getClass().getResource("avatar.fxml"); 
ResourceBundle resources = ResourceBundle.getBundle("myResource"); 
FXMLLoader fxmlLoader = new FXMLLoader(location, resources); 
Pane root = (Pane)fxmlLoader.load(); 
MyController controller = (MyController)fxmlLoader.getController(); 

但是當我嘗試運行該程序,javaFX拋出異常,並要求圖片標記中的網址不應該爲空。
有人可以告訴我我做錯了什麼?
非常感謝。
P/S代碼被簡化爲您的閱讀方便。我正在使用Java 8.

+1

什麼是JXML文件? – 2015-02-23 19:59:38

回答

2

由於錯誤提示,必須使用圖像數據的URL初始化Image

如果您希望能夠動態更改顯示的圖像,您需要將ImageView(可以初始化爲「空白」,即沒有圖像)注入控制器,然後將圖像設置在其上如你所需。因此,在FXML

只是做

<ImageView fx:id="myImageView" /> 

,並在控制器做

public class MyController { 

    @FXML 
    private ImageView myImageView ; 

    public void initialize() { // or in an event handler, or when you externally set the image, etc 
     Path imageFile = Paths.get("/path/to/image/file"); 
     myImageView.setImage(new Image(imageFile.toUri().toURL().toExternalForm())); 

    } 
}