繁体   English   中英

Java Swing:无法使用getResource加载图像

[英]Java Swing: unable to load image using getResource

我试图隔离试图将图像添加到类目录时问题可能出在哪里。 (这样做是为了在我导出为可运行的JAR时,映像包含在包中)。

因此,我已经将Strawberry.jpg文件放在“ C:\\ Users \\ sean \\ workspace \\ myApps \\ src \\ testing”中,您能告诉我我所缺少的内容吗? 谢谢!

package testing;

import java.awt.*;
import javax.swing.*;

public class IconTest {

    public static void main(String[] arguments) {

        JFrame frame1 = new JFrame();
        frame1.setTitle("Frame1");
        frame1.setSize(500, 500);
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        FlowLayout flo = new FlowLayout();
        frame1.setLayout(flo);

        JLabel label1 = new JLabel(new ImageIcon(
            IconTest.class.getResource("strawberry.jpg")));
        frame1.add(label1);
        frame1.setVisible(true);
    }
}

我将使用SomeClass.class.getResourceAsStream("...")如以下示例所示:

public static void main(String[] arguments) throws IOException {

    JFrame frame1 = new JFrame();
    frame1.setTitle("Frame1");
    frame1.setSize(500, 500);
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    FlowLayout flo = new FlowLayout();
    frame1.setLayout(flo);

    InputStream resourceAsStream = IconTest.class.getResourceAsStream("strawberry.jpg");
    Image image = ImageIO.read(resourceAsStream);

    JLabel label1 = new JLabel(new ImageIcon(image));
    frame1.add(label1);
    frame1.setVisible(true);
}

将图像文件放在已编译类所在的目录中,并通过在文件名前添加“ /”来更改代码中的路径:

JLabel label1 = new JLabel(new ImageIcon(
        IconTest.class.getResource("/strawberry.jpg")));

在类路径中搜索资源。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM