Search code examples
javaswingintellij-ideajarembedded-resource

After buiding java app, some GUI components does not work properly, but during IDE tests everything is fine. Why?


I am working on GUI java project which contains FileChooser(combined with JLabel it becomes ImageChooser) and JTextArea (inside of JScrollPane). Both of these components are inside of JPanel.

When ever I ran it inside of IntelliJ Idea (version 2017.2.4)everything works fine:

UI when executed from IDE

But if I build Artifacts and create .jar file, then image inside of JLabel is not initialized and the size(height) of JTextArea becomes minimal(though minimal value is set to 200):

IU when executed from .jar file

I suspect that ImageIcon cannot be initialized due to relative path I provide:

...
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);
}

However, I've tried options with relative path like main/resources/ and /main/resources/ , but none of them worked both in IDE and .jar executable.

Is it a problem with a path? If yes, why does it affect JTextArea's size?

P.S.

JTextArea's size becomes normal if there is an image in JLabel.


Solution

  • You are right, the way you fetch resources is problematic in a jar.

    The way you should access them:

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

    This method supports relative paths. Just make sure your src/main/resources directory is properly marked as a 'Resource Root' in IntelliJ IDEA.