问题描述
这是代码:
import java.awt.*;
import java.applet.*;
public class anim1 extends Applet{
public void paint (Graphics g)
{
g.drawString("",400,300);
}
public static void main(String ad[])
{
anim1 a=new anim1();
Graphics g1;
a.paint(g1);
}
}
它说 g1 没有初始化.但是我如何初始化一个抽象类?
It says that g1 is not initialized. But how do I initialize an abstract class?
推荐答案
这里有两个问题1:
Graphics g1;
a.paint(g1);
并且您收到 G1 未初始化的错误.那是因为变量 g1 从未设置为任何内容,这会导致编译错误.要编译代码,您至少需要这样做:
And you are getting the error that G1 is not initialized. That's because the variable g1 is never set to anything, and that causes a compile error. To get the code to compile, you would need to, at the very least do this:
Graphics g1 = null;
a.paint(g1);
然而,这显然不会帮到你太多.当您尝试运行代码时,您将收到 NullPointerException.为了真正使您的图形绘制,您需要这样做:
However, that obviously won't help you out too much. You'll get a NullPointerException when you try to run your code. In order to actually cause your graphics to draw you need to this:
anim1 a=new anim1();
Graphics g1 = anim1.getGraphics();
a.paint(g1);
但是,这仍然不起作用,因为 Anim1 不会出现在屏幕上.要让它出现在屏幕上,你需要像这样:
However, that still won't work because Anim1 will not appear on the screen. To get it to appear on the screen you need something like:
import java.awt.*;
import javax.swing.*;
import java.applet.*;
public class So1 extends Applet{
public void paint (Graphics g)
{
g.drawString("hello",40,30);
}
public static void main(String ad[])
{
JFrame jp1 = new JFrame();
So1 a=new So1 ();
jp1.getContentPane().add(a, BorderLayout.CENTER);
jp1.setSize(new Dimension(500,500));
jp1.setVisible(true);
}
}
现在请注意,我们实际上并没有自己调用paint() 函数.这由 awt 处理,它实际上选择图形上下文,并为我们调用我们的绘制函数.但是,如果您愿意,您可以传入任何您想要的图形对象并要求它在其上绘制.(所以如果你想把你的组件绘制到图像上,你可以这样做)
Now notice, we don't actually call the paint() function ourselves. That's handled by the awt, which actually picks the graphics context, and calls our paint function for us. If you want, though, you can pass in any graphics object you want and ask it to draw on to that. (so if you want to draw your component onto an image, you can do it)
(注意,我把类名从 anim1 改成了 So1)
(note, I changed the classname from anim1 to So1)
这篇关于如何在 Java 中初始化 Graphics 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!