最近遇到一问题,原题是在一个Frame上实现绘制hello world的字符串,要求写完hello后等待1秒再写world,1秒种后把Frame上的字体串变成红色.题目不难,但最开始我的想法是.用一个类extends Frame类并implements Runnable接口,在该类中定义一个Graphics变量,然后在该类的paint方法中把用paint的参数对定义的变量进行赋值.代码如下:
class Frame extends Frame implements Runnable{
Graphics graphics;
Frame(){
                //窗口设计;
}
public void paint(Graphics g){
this.graphics=g;
}
public void run() {
graphics.drawString("hello world",30,70);
}
}
然后在main方法中生成该类的对象frame,new Thead(frame).start()应该就行了.
以上代码虽然不是原题的要求,但是要在run方法里稍做处理就可以实现了.
问题是以上代码中的graphics变量总是会抛出空指针异常,十分不解,明明不是已经在paint方法中对其进行赋值了.
十分不解,向各位老师前辈求教!!
(另外:该方法若是在paint方法中对Frame进行处理的话,有时会出现"不稳定"的现象,即生成的窗口可能同是出现paint方法和run方法同时对窗口的处理,也可能只出现只有paint方法对Frame的处理,同样不解.求教!!!)

解决方案 »

  1.   

    只有当面板变得可视后才能提供它的Graphics g还有public void paint(Graphics g)这里的g并不是始终是同一个对象, 面板大小改变等 都会传进新的g
      

  2.   

    //程序可以这样写 (比较粗糙)import java.awt.*;
    class MyFrame extends Frame implements Runnable{ 
    boolean isred=false;
    String str="";
    MyFrame(){ 
                    //窗口设计; 
    this.setSize(400,300);
    this.setVisible(true);

    public void paint(Graphics g){ 
    //this.graphics=g; 
    if (isred==true)
    g.setColor(Color.red);
    g.drawString(str,30,70); 

    public void run() { 
    //graphics.drawString("hello world",30,70); 
    try{
    str="hello";
    repaint();
    Thread.sleep(1000);
    str="hello world";
    repaint();
    Thread.sleep(1000);
    isred=true;
    repaint();
    } catch(Exception e){
    }

    public static void main(String[] args)
    {
    MyFrame f=new MyFrame();
    new Thread(f).start();
    }
      

  3.   

    只是,对面板进行绘制时总会调用paint方法.而对于不同的Graphics对象,当paint方法被调用时,就会把新的Graphics对传给定义的变量,我感觉这个变量应该和当前面板的Graphics对象是相等的.不知道这样理解有没有问题...
    另外,感谢老师对原题的解答!~