为什么工具栏在使用IntelliJ创建的可执行Jar中不可见?

时间:2016-07-28 14:35:11

标签: image user-interface intellij-idea jar imageicon

我使用IntelliJ为jar应用程序创建了一个GUI文件。但是,当我运行该文件时,我看不到包含toolbar按钮的ImageIcon用于不同的功能位置。在浏览stackoverflow时(如此处:Java Swing ImageIcon, where to put images?),我发现图像的文件路径可能是个问题。目前我使用以下代码:

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

使用以下方法获取currentPath变量:

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

createImageIcon方法具有以下代码:

 /**
     * 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;
    }

当我在intelliJ中运行它时,此代码工作正常,但是,当我运行jar时,工具栏不可见。我还尝试直接在src文件夹下移动images文件夹,然后执行以下操作:

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

但这给了我一个NullPointerException。我哪里错了?

1 个答案:

答案 0 :(得分:1)

您无需在此处使用当前路径。由于您使用的是IntelliJ,只需将文件夹标记为资源根目录,方法是选择src文件夹并右键单击它以查找

  

将目录标记为

将图像文件夹移动到src文件夹下。然后使用以下代码将图像图标设置为按钮

Java - setting classpath

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

将createToolIcon方法放在同一个类文件中,或者创建一个单独的类并使用该类调用该方法。

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