如何在Java中初始化Graphics对象? [英] How do I initialize a Graphics object in Java?

查看:1527
本文介绍了如何在Java中初始化Graphics对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码:

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处理,实际上选择图形上下文,并为我们调用我们的paint函数。如果你想,但是,你可以传入任何你想要的图形对象,并要求它来。 (所以如果你想绘制你的组件到一个图像,你可以这样做)

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对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆