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

标签 java eclipse swing jlabel javax.imageio

我尝试使用 JLabel 显示图像。这是我的项目导航器: enter image description here

来自 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();
        }

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

图片路径是否错误?

最佳答案

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

image = ImageIO.read(getClass().getResource(path));
-or-
image = ImageIO.read(MyClass.class.getResource(path));

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

请参阅 embedded resource 上的 wiki 。另请参阅getResource()

<小时/>

更新测试运行

enter image description here

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

关于java - 将图像加载到 JLabel 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21856648/

相关文章:

java - 使用java将日期和时间戳插入数据库的最佳方法

eclipse - 调试时复制对象

java - 从 Swing tableModel 中删除空白 propertyColumn

Java:为不同层组件定义 mouseAdapter 的 jLayeredPane 问题

Java 抽象表模型 : getValueAt does not use updated data

java - 从线程中读取数据(在 Servlet 中)

java - 需要一个函数来限制一条线(通过其坐标已知)的长度

java - 如何监控java程序的内存使用情况?

java - Eclipse崩溃

java - 如何获取 Eclipse 中方法抛出的具体异常列表