to pdev(达子): 你的修改是错误的,编译不通过,首先,不能在静态上下文中不能出现非静态方法init(),其次,就是改为 pi.init(), 编译通过后,还是和原来一样,出现空指针异常。to foryouever() : 你能不能修改一下我的程序,然后贴出来让我看看? to 其他高手: 我在书上看到一段话,感觉和这个问题有关系,但是我不清楚如何实际应用到这个程序中,你们谁能帮我看看? There are three caveats that you need to be aware of when using images. They both relate to the timing of when you try to create them. a) First, you cannot call the getImage() method of an applet before the init() method of that applet is called. If you do, you will receive a null pointer exception, since the method depends upon the AppletContext object that is provided to the applet by the browser in which it is running. To avoid this problem, don’t put calls to getImage in constructors or initializers of applets. b) Second, if you have an Applet that is not running in a browser, then there will be no AppletContext object, and the getImage() method will not work. You can get images in Applications using the Toolkit object. c) Third, if you use the createImage() method of a component, the component must have been “realized”—that is, actually displayed—before you call that method.
import java.awt.*;public class PaintImage extends Applet
{
public static void main(String args[])
{
Frame f=new Frame("PaintImage Example");
PaintImage pi=new PaintImage();
f.add(pi);
f.setBounds(100,100,500,500);
f.setVisible(true);
//我的修改
init();
//修改结束
}
private Image im; public void init()
{
im = createImage(300, 200);
Graphics imgc = im.getGraphics();
imgc.setColor(Color.yellow);
imgc.fillRect(0, 0, 300, 200);
imgc.setColor(Color.blue);
imgc.fillOval(50, 50, 100, 100);
} public void paint(Graphics g)
{
g.drawImage(im, 25, 80, this);
}
}
你的修改是错误的,编译不通过,首先,不能在静态上下文中不能出现非静态方法init(),其次,就是改为 pi.init(), 编译通过后,还是和原来一样,出现空指针异常。to foryouever() :
你能不能修改一下我的程序,然后贴出来让我看看?
to 其他高手:
我在书上看到一段话,感觉和这个问题有关系,但是我不清楚如何实际应用到这个程序中,你们谁能帮我看看? There are three caveats that you need to be aware of when using images. They both relate to the timing of when you try to create them.
a) First, you cannot call the getImage() method of an applet before the init() method of that applet is called. If you do, you will receive a null pointer exception, since the method depends upon the AppletContext object that is provided to the applet by the browser in which it is running. To avoid this problem, don’t put calls to getImage in constructors or initializers of applets.
b) Second, if you have an Applet that is not running in a browser, then there will be no AppletContext object, and the getImage() method will not work. You can get images in Applications using the Toolkit object.
c) Third, if you use the createImage() method of a component, the component must have been “realized”—that is, actually displayed—before you call that method.