2017-09-22 30 views
0

我正在处理包含FileChooser(与JLabel成为ImageChooser)和JTextArea(JScrollPane内部)的GUI java项目。这两个组件都在JPanel内部。构建java应用程序后,某些GUI组件无法正常工作,但在IDE测试期间一切正常。为什么?

当过我跑了它的IntelliJ IDEA的内部(版本2017年2月4日),一切工作正常:

UI when executed from IDE

但是,如果我建立文物和创建.jar文件,然后在图片内的JLabel不初始化和JTextArea中的尺寸(高度)变得最小(虽然最小值被设定为200):

IU when executed from .jar file

我怀疑的ImageIcon不能由于相对于路径I初始化提供:

... 
imagePath = "src/main/resources/" + item.getImageName(); 
//item.getImageName() returns a proper image name, tested with 
//System.out.println() and there is a proper image in that folder. 
ImageIcon img = new ImageIcon(imagePath); 
img = ImageManager.resize(img); 
... 
//Resize function in ImageManager class 
public static ImageIcon resize(ImageIcon imageIcon, int size){ 
    return resize(imageIcon, size, size); 
} 

public static ImageIcon resize(ImageIcon icon){ 
    return resize(icon, defaultSize); 
} 

与像主/资源的相对路径。然而,我已经试过选项/和/主/资源/,但他们都不在这两个IDE和.jar的可执行的工作。

这是路径问题吗? 如果是,为什么会影响JTextArea的大小?

P.S.

如果JLabel中有图像,则JTextArea的大小将变为正常。

回答

1

你是对的,你获取资源的方式在jar中是有问题的。

你应该访问它们的方式:

ImageIcon img = new ImageIcon(this.getClass().getClassLoader().getResource(item.getImageName())); 

此方法支持相对路径。只需确保您的src/main/resources目录在IntelliJ IDEA中正确标记为“Resource Root”。

+0

你真的不应该在你的档案中包含'src',这将包括你的源代码 - 可能是错误的,因为我不使用IntelliJ,但是你永远不应该在代码中引用'src' – MadProgrammer

+0

@MadProgrammer这就是对。在档案中,您只需确保资源包含在内,就是这样。我相信IntelliJ IDEA在设置工件设置时会默认这样做。 – Thibstars

相关问题