我是Applets的新手,我試圖讓一些基本知識變得舒適 - 比如如何在一箇中顯示一個jpg圖像。我已經閱讀了我認爲Applets上的Java教程的相關部分,我不明白爲什麼這不起作用,我得到的只是一個空白的小程序區域。 「/cards/as.jpg」 - 該文件存在於運行applet的目錄的子目錄中。任何人都可以看到我做錯了什麼?我很茫然。爲什麼這個小程序不工作/顯示圖像?
import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestApplet extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
}
catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
private void createGUI() {
JPanel newContentPane = new JPanel();
ImageComponent card = new ImageComponent();
card.setImage(getCodeBase() + "/cards/as.jpg");
newContentPane.add(card);
newContentPane.setOpaque(true);
setContentPane(newContentPane);
}
}
import java.awt.*;
import javax.swing.JComponent;
import javax.imageio.*;
import java.net.*;
import java.io.*;
/**
A component that draws an Image.
*/
public class ImageComponent extends JComponent {
private Image image;
private String url;
public ImageComponent() {
image = null;
url = null;
}
public void setImage(String urlCardName) {
url = urlCardName;
if (url != null) {
try {
image = ImageIO.read(new URL(url));
}
catch (IOException e)
{
e.printStackTrace();
}
}
else {
image = null;
}
this.repaint();
}
public void paintComponent(Graphics g) {
if (image == null) return;
// draw the images in the upper-left corner of the component
g.drawImage(image, 0, 0, null);
}
}
getCodeBase()返回什麼?'setImage()'期望什麼? – 2011-06-05 23:55:40