我编写了这段代码,用于在applet屏幕上显示一些简单的图片,但图片并没有显示,直到我调整applet窗口的大小,我该怎么做才能克服它?
public class Test extends JApplet {
public void init () {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createGUI();
}
});
}
public void start() {
}
public void createGUI() {
getContentPane().add(new GUIThing(getImage(getCodeBase(), "gladiator.gif")));
}
}
public class GUIThing extends JPanel {
Image image;
public GUIThing(Image i2) {
image=i2;
}
public void paintComponent(Graphics g) {
Graphics2D g2=(Graphics2D) g;
g2.drawImage(image,100,100,100, 100, null);
}
}
答案 0 :(得分:1)
尝试将applet上下文传递给drawImage
方法,这样可以在加载图像时通知appet,它会自行重绘
g2.drawImage(image,100,100,100, 100, this);
而且,如果您真的很绝望,请在invalidate()
方法中致电repaint()
start
更新示例
这是我使用的代码。我没有加载图片的问题:
public class TestApplet extends JApplet {
public void init() {
System.out.println("Init..." + EventQueue.isDispatchThread());
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
createGUI();
}
});
}
public void start() {
System.out.println("Start..." + EventQueue.isDispatchThread());
}
public void createGUI() {
URL documentBase = getDocumentBase();
System.out.println(documentBase);
System.out.println(getCodeBase());
// file:.../build/TestApplet.html
// file:.../build/classes/
Image image = getImage(documentBase, "MT-vol-6-STOP-image-Kogumiko-megatokyo-11434773-1559-1852.jpg");
System.out.println("image = " + image);
getContentPane().add(new GUIThing(image));
}
public class GUIThing extends JPanel {
Image image;
public GUIThing(Image i2) {
image = i2;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(image, 0, 0, this);
g2.setColor(Color.RED);
g2.drawLine(0, 0, getWidth(), getHeight());
}
}
}
哇,自从我玩applet以来已经很久了。我将代码从使用代码库更改为它似乎工作的文档库。我正在加载1559x1852像素的图像,几乎没有延迟(本地)
同样仔细检查HTML文件中的applet标记。我正在使用
<APPLET codebase="classes" code="stack/TestApplet.class" width=350 height=200></APPLET>
通过applet查看器。请注意,代码库与文档库不同!!
我的图片与HTML文件位于同一位置