构建 java 应用程序后,某些 GUI 组件无法正常工作,但在 IDE 测试期间一切正常。为什么?
After buiding java app, some GUI components does not work properly, but during IDE tests everything is fine. Why?
我正在开发 GUI java 项目,其中包含 FileChooser(与 JLabel 结合后成为 ImageChooser)和 JTextArea(在 JScrollPane 内部)。这两个组件都在 JPanel 中。
每当我在 IntelliJ Idea(版本 2017.2.4)中 运行 它时,一切正常:
UI when executed from IDE
但是,如果我构建 Artifacts 并创建 .jar 文件,则 JLabel 内部的图像未初始化,并且 JTextArea 的大小(高度)变为最小(尽管最小值设置为 200):
IU when executed from .jar file
我怀疑由于我提供的相对路径导致ImageIcon无法初始化:
...
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);
}
但是,我已经尝试过具有相对路径的选项,例如 main/resources/ 和 /main/resources/ ,但是 none 它们在 IDE 和 .jar 中都有效可执行文件。
是路径问题吗?
如果是,为什么会影响 JTextArea 的大小?
P.S.
如果JLabel中有图片,JTextArea的大小就正常了
你是对的,你在 jar 中获取资源的方式是有问题的。
访问它们的方式:
ImageIcon img = new ImageIcon(this.getClass().getClassLoader().getResource(item.getImageName()));
该方法支持相对路径。只需确保您的 src/main/resources
目录在 IntelliJ IDEA 中正确标记为 'Resource Root'。
我正在开发 GUI java 项目,其中包含 FileChooser(与 JLabel 结合后成为 ImageChooser)和 JTextArea(在 JScrollPane 内部)。这两个组件都在 JPanel 中。
每当我在 IntelliJ Idea(版本 2017.2.4)中 运行 它时,一切正常:
UI when executed from IDE
但是,如果我构建 Artifacts 并创建 .jar 文件,则 JLabel 内部的图像未初始化,并且 JTextArea 的大小(高度)变为最小(尽管最小值设置为 200):
IU when executed from .jar file
我怀疑由于我提供的相对路径导致ImageIcon无法初始化:
...
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);
}
但是,我已经尝试过具有相对路径的选项,例如 main/resources/ 和 /main/resources/ ,但是 none 它们在 IDE 和 .jar 中都有效可执行文件。
是路径问题吗? 如果是,为什么会影响 JTextArea 的大小?
P.S.
如果JLabel中有图片,JTextArea的大小就正常了
你是对的,你在 jar 中获取资源的方式是有问题的。
访问它们的方式:
ImageIcon img = new ImageIcon(this.getClass().getClassLoader().getResource(item.getImageName()));
该方法支持相对路径。只需确保您的 src/main/resources
目录在 IntelliJ IDEA 中正确标记为 'Resource Root'。