gpt4 book ai didi

java - JWindow 不会显示 ImageIcon

转载 作者:行者123 更新时间:2023-11-29 09:28:55 25 4
gpt4 key购买 nike

我想知道为什么我的 JWindow 不显示我的图像。我有这段代码:

JWindow window = new JWindow();
JPanel jp = new JPanel();
JLabel l = new JLabel(new ImageIcon("GenericApp.png"));
jp.add(l);
window.add(jp);
window.setBounds(500, 150, 300, 200);
window.setVisible(true);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
window.setVisible(false);

编辑:我的代码现在是(回到原来的):

final JWindow window = new JWindow();
JPanel jp = new JPanel();
JLabel l = new JLabel(new ImageIcon(Asset.class.getResource("GenericApp.png")));
jp.add(l);
window.add(jp);
window.setBounds(500, 150, 300, 200);
window.setVisible(true);
try{
Thread.sleep(5000);
}catch(InterruptedException e){
e.printStackTrace();
}
window.setVisible(false);

是的,我决定使用Thread.sleep()。我的 jar 从/Users/thomasokeeffe/Desktop/eclipse/AI/AI 执行,这就是图片所在的位置。启动时我仍然得到一个空白的 JWindow。 System.out.println(new File("GenericApp.png").exists()); 返回 true。

又一次编辑 如果我把图片放在 jar 文件中,对我来说会更容易吗?最奇怪的事情之一是,当我不在应用程序中运行 jar 并将图片放在工作目录中时,它仍然显示一个空白矩形......

编辑 到目前为止,我已尝试使用 URL,并通过获取 user.dir 系统属性进行调试。我现在有这两行代码来获取图片(图片与类在同一个包中):

URL url = this.getClass().getResource("GenericApp.png");
JLabel l = new JLabel(new ImageIcon(url));

我也尝试过使用 InputStream:

InputStream is = this.getClass().getResourceAsStream("GenericApp.png");
Image image = null;
try {
image = ImageIO.read(is);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

我做错了什么?

最佳答案

如果图像在您的 jar 中或通常在您的类路径中,您可以通过以下方式获取它

getClass().getResource(resourcePath);

资源路径以类路径的根为根。

例如,与您的类(class)在同一目录中的图像将是

new JLabel(new ImageIcon(getClass().getResource("GenericApp.png")));

关于java - JWindow 不会显示 ImageIcon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31497007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com