How do I initialize a Graphics object in Java?

93,594

Solution 1

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)

Solution 2

An applet doesn't need a main method like a regular Java application does. I'd recommend starting with Sun's Applets Tutorial. In particular you may want to skip ahead to the section Life Cycle of an Applet to see how the Graphics object is handled within the applet.

Solution 3

All you need to do is simply remove the main method like so:

import java.awt.*;
import java.applet.*;

public class anim1 extends Applet {

    public void paint (Graphics g) {
        g.drawString("Hello",100,100);
    }
}
Share:
93,594
Admin
Author by

Admin

Updated on October 16, 2020

Comments

  • Admin
    Admin over 3 years

    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?