I am having a hard time figuring out how to show an Image (or ImageIcon) in a Java applet. The following is my code. The picture (test.bmp) does exist and is on the D drive but when I run this I get the applet window with nothing in it. Can somebody tell me what I am missing to make the ImageIcon show?
public class Form1 extends JApplet {
ImageIcon i;
public void init(){
i = new ImageIcon("D:\test.bmp");
}
public void paint(Graphics g){
i.paintIcon(this, g, 0, 0);
}
}
Thanks, Steve.
解决方案
Referencing your image through an absolute local file path might not work when you run your applet from a server. Use the ImageIcon (URL location) constructor and Have the URL point to the image resource on the server. Use the JApplet.getCodeBase() to determine where your applet originates and append the file name to it.
public class Form1 extends JApplet {
Image i;
public void init() {
try {
i = ImageIO.read(new URL(getCodeBase(), "test.bmp"));
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void paint(Graphics g) {
g.drawImage(i, 0, 0, null);
}
}
Edit: ImageIO supports BMP and the changed sample works for me.
Edit 2: If it still doesn't display the image, try "../test.bmp" because when you run an applet from lets say Eclipse it has the bin directory as the codebase.
Edit 3: If you put your test.bmp into the jar or on the classpath, you can load it using the same way but replacing
new URL(getCodeBase(), "test.bmp")
with
Form1.class.getResource("test.bmp")