java graphics 初始化,如何在Java中初始化Graphics对象?

this is the code:

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);

}

}

It says that g1 is not initialized. But how do I initialize an abstract class?

解决方案

Well there are two issues here 1:

Graphics g1;

a.paint(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);

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);

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);

}

}

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)

(note, I changed the classname from anim1 to So1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值