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

Why is the toolbar not visible in executable Jar created using IntelliJ?

我已经使用 IntelliJ 为我的 GUI 应用程序创建了一个 jar 文件。但是,当我 运行 文件时,我看不到 toolbar,其中包含用于不同功能的带有 ImageIcon 的按钮。在查看 Whosebug(如此处: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 文件夹下,然后执行以下操作:

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

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

这里不需要使用当前路径。由于您在 IntelliJ 中工作,只需将文件夹标记为资源根目录,方法是选择 src 文件夹并右键单击它以找到

mark directory as

将images文件夹移动到src文件夹下。然后使用下面的代码将图片图标设置为按钮

Java - setting classpath

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

并将 createToolIcon 方法放在同一个 class 文件中,或者创建一个单独的 class 并使用该 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;    
}