2015-02-23 36 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())); 

    } 
}