1

I have created a jar file for my GUI application using IntelliJ. However, when I run the file, I cannot see the toolbar which contains the buttons with ImageIcon for different functionaltites. On looking around over stackoverflow (like here: Java Swing ImageIcon, where to put images?), I found that the file path for the images could be an issue. At present I am using the following code:

OpenImagingFileButton = new JButton(createImageIcon(currentPath.concat("/src/main/java/uni/images/open-file-icon-img.png")));  

The currentPath variable is obtained using this:

final String currentPath = currentRelativePath.toAbsolutePath().toString();

And the createImageIcon method has the following code:

 /**
     * Returns an ImageIcon, or null if the path was invalid.
     */
    protected static ImageIcon createImageIcon(String path) {
        ImageIcon toolBarImage = new ImageIcon(path);
        Image image = toolBarImage.getImage(); // transform it
        Image newImg = image.getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH); // scale it the smooth way
        toolBarImage = new ImageIcon(newImg);  // transform it back
        return toolBarImage;
    }

This code works perfectly when I run it in intelliJ, however, the toolbar is not visible when I run the jar. I also tried moving the images folder directly under src folder and then doing this:

ImageIcon(this.getClass().getResource("/images/open-file-icon-img.png"));

But this gives me aNullPointerException. Where am I going wrong?

Community
  • 1
  • 1
novicegeek
  • 773
  • 2
  • 9
  • 29

1 Answers1

1

You don’t need to use the current path here. Since you are working in IntelliJ, simply mark the folder as resources root, by selecting the src folder and right clicking it to find

mark directory as

Move the images folder under the src folder. Then use the following code to set the image icon as a button

Java - setting classpath

openProject = new JButton();
openProject.setIcon(createToolIcon("/images/openProject.png"));

And place the createToolIcon method in the same class file or create a separate class and call the method using that class.

public static ImageIcon createToolIcon(String path) {  
URL url = System.class.getResource(path);   
if(url == null) {
    System.err.println("Unable to load Image: " + path);    
}   
ImageIcon icon = new ImageIcon(url);    
Image img = icon.getImage();  
Image newimg = img.getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)
ImageIcon newIcon = new ImageIcon(newimg);    
return newIcon;    
}
Community
  • 1
  • 1
JstRoRR
  • 3,693
  • 2
  • 19
  • 20
  • This code works!! Moreover, I was not aware of the mark directory functionality in IntelliJ. Now everything seems to be in the right place. Thanks a ton :) – novicegeek Jul 28 '16 at 16:35