我想知道为什么我的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并将图片放在工作目录中时,它仍然显示一个空白的矩形.
到目前为止,我已经尝试使用编辑,并通过获取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();
}我做错了什么?
发布于 2015-07-19 01:47:35
如果图像在您的jar中,或者通常在您的类路径中,您可以通过
getClass().getResource(resourcePath);资源路径根植于类路径的根。
例如,与类相同的dir中的图像将是
new JLabel(new ImageIcon(getClass().getResource("GenericApp.png")));发布于 2015-07-19 01:16:14
Gui代码可以处理事件调用。当您的函数在主线程中执行时,屏幕上不会发生任何变化。屏幕上的实际更改是在调用代码之间完成的。这意味着您的功能应该尽快完成。
所以为了得到一些东西来证明你需要回来。
若要在以后执行的代码中排队,可以使用javax.swing.Timer:
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);
Timer timer = new Timer(5000, new ActionListener(){
void actionPerformed(ActionEvent e){
window.setVisible(false);
}
});
timer.setRepeats(false);//only do this once
timer.start();https://stackoverflow.com/questions/31497007
复制相似问题