从 Netbeans Java 中的资源加载 PNG

问题描述 投票:0回答:1

我有一个项目,正在从项目资源加载 *.PNG 图像。我发现一些 PNG 文件加载正常,而其他文件则无法通过 .getClass().getResource(fileName) 找到,返回 null。

失败似乎取决于 PNG 的实际格式。我有一些旧的 PNG 可以正常加载,但是当我在 GIMP 中制作新的 PNG 时,它们始终无法加载。 (呃 - 我忘记了我是如何制作旧的......)

图片均为16x16,均位于项目源码包/资源中。

我尝试在 GIMP 中以多种不同格式保存 PNG,但都失败了。

我正在加载它们:

protected ImageIcon loadIcon(String fileName) {
    Class<?> cls = this.getClass();
    URL url = cls.getResource(fileName);
    // ⬅️ this is the point of failure as url will be null

    if (url == null) {
        return null;
    }

    Image image = null;
    try {
        image = ImageIO.read(url);
    } catch (IOException ex) {
        msglistener.Send(new EMsgData.Builder().setType(EMsgData.MsgType.DEBUG).setSender(this).setText("Load Icon Failed").build());
    }

    if (image == null) {
        return null;
    }

    return new ImageIcon(image);
}

参数通常是: ImageIcon 图标 = loadIcon("/Pencil.png");

我附上了两张图片。第一个失败,第二个成功。

java png
1个回答
0
投票

提示:您可以使用

Objects.requireNonNull
更方便地检查空值。例如:

ImageIcon iconA = new ImageIcon ( Objects.requireNonNull ( urlA ) );

我不知道你的问题是什么。但我可以给你一个可行的例子。我使用了您的两个链接文件,并且都对我有用。

如果您使用 Apache Maven 来驱动项目的构建,请在

resources
文件夹中的
main
文件夹顶部创建一个名为
src
的文件夹。当您构建项目时,在
resources
中找到的任何嵌套文件和文件夹都将被复制到最终工件(您的 JAR 文件)中。

这是 IntelliJ 的屏幕截图。在 NetBeans 中执行相同的操作应该会产生相同的效果。

这是此示例应用程序的代码。

package work.basil.example;

import javax.swing.*;
import java.awt.*;
import java.net.URL;
import java.util.Objects;

/**
 * Demonstrate loading PNG files as ImageIcon for display in Swing app.
 */
public class App
{
    public static void main ( String[] args )
    {
        System.out.println ( "Hello World!" );
        javax.swing.SwingUtilities.invokeLater ( new Runnable ( )
        {
            public void run ( )
            {
                createAndShowGUI ( );
            }
        } );
    }

    private static void createAndShowGUI ( )
    {
        // JFrame
        JFrame.setDefaultLookAndFeelDecorated ( true );
        JFrame frame = new JFrame ( "Icons" );
        frame.setLayout ( new FlowLayout ( ) );
        frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );

        // Widgets
        URL urlA = App.class.getResource ( "/4eS8f.png" );
        ImageIcon iconA = new ImageIcon ( Objects.requireNonNull ( urlA ) );
        JLabel labelA = new JLabel ( Objects.requireNonNull ( iconA ) );

        URL urlB = App.class.getResource ( "/ENwj0.png" );
        ImageIcon iconB = new ImageIcon ( Objects.requireNonNull ( urlB ) );
        JLabel labelB = new JLabel ( Objects.requireNonNull ( iconB ) );

        frame.getContentPane ( ).add ( new JLabel ( "Hello World" ) );
        frame.getContentPane ( ).add ( labelA );
        frame.getContentPane ( ).add ( labelB );
        frame.getContentPane ( ).add ( new JLabel ( "The End" ) );

        // Display.
        frame.pack ( );
        frame.setSize ( 400 , 200 );
        frame.setVisible ( true );
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.