将图像加载到 JLabel 中不起作用

MaT*_*TTP 3 java eclipse swing jlabel javax.imageio

我尝试使用显示图像JLabel。这是我的项目导航器: 在此输入图像描述

我想SettingsDialog.java使用以下代码显示图像:

        String path = "/images/sidebar-icon-48.png";
        File file = new File(path);
        Image image;
        try {
            image = ImageIO.read(file);

            JLabel label = new JLabel(new ImageIcon(image));
            header.add(label); // header is a JPanel
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
Run Code Online (Sandbox Code Playgroud)

代码抛出异常:无法读取输入文件!

是不是图片路径不对?

Pau*_*tha 5

不要从文件中读取,而是从类路径中读取

image = ImageIO.read(getClass().getResource(path));
-or-
image = ImageIO.read(MyClass.class.getResource(path));
Run Code Online (Sandbox Code Playgroud)

当您使用File对象时,您是在告诉程序从文件系统中读取,这将使您的路径无效。不过,当从类路径读取时,您使用的路径是正确的,正如您应该做的那样。

请参阅有关嵌入式资源的 wiki 。另请参阅getResource()


更新测试运行

在此输入图像描述

package org.apache.openoffice.sidebar;

import javax.swing.*;

public class SomeClass {
    public SomeClass() {
        ImageIcon icon = new ImageIcon(
              SomeClass.class.getResource("/images/sidebar-icon-48.png"));
        JLabel label = new JLabel(icon);

        JFrame frame = new JFrame("Test");
        frame.add(label);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                new SomeClass();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)