【发布时间】:2015-10-08 10:12:24
【问题描述】:
我想知道为什么我的 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();
}
我做错了什么?
【问题讨论】:
-
Thread.sleep(5000);可能不会有帮助。有关详细信息,请参阅 Concurrency in Swing 和 How to use Swing Timers。窗口真的出现了吗? -
我不知道将代码放在哪里,在计时器之前、之后还是在计时器中。
-
部分代码位于
Timer,尤其是setVisible(false)。图像存储在哪里(在项目源的上下文中)? -
我的 jar 在应用程序中。图片在带有 jar 的 java 文件夹中
-
假设图像与 Jar 位于同一目录中并且程序从与 Jar 相同的位置执行,那么您的图像应该加载。尝试改用
JLabel(new ImageIcon(ImageIO.read(new File("GenericApp.png")))),如果无法读取图像,则会抛出IOException
标签: java swing embedded-resource imageicon