Amol
Amol

Reputation: 27

Java Draw Shapes Error

I have to write a program using applet it should have 3 Button line,rect,circle.Upon clicking on them the desired shape should be drawn.

I have written the following code but it is showing error that Graphics is not initialized. What to do now?

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Drawshapes extends Applet implements ActionListener
{

    Button line,rect,circle;
    public void init()
    {

        line=new Button("Line");

        rect=new Button("Rectangle");
        circle=new Button("Circle");

        add(line);
        add(circle);
        add(rect);

        line.addActionListener(this);
        rect.addActionListener(this);
        circle.addActionListener(this);
    }

    public void paint(Graphics g)
    {
    }

    public void actionPerformed(ActionEvent ae)
    {

        Graphics g;
        if(ae.getSource()==line)
        {
            g.drawLine(0,100,100,10);
        }
        else if(ae.getSource()==rect)
            {
                g.drawRect(10,10,60,50);
            }
        else
        {
                g.drawOval(10,10,50,50);
        }
    }
}

Upvotes: 1

Views: 1322

Answers (3)

Reimeus
Reimeus

Reputation: 159844

As with all local variables, the Graphics g is required to be initialized. However, doing custom painting from the ActionListener is a bad idea. Use the Graphics object in the paint method which has been properly instantiated.

Set a flag in the ActionListener and then call repaint:

For example in ActionListener for line:

drawLine = true;
repaint();

paint:

@Override
public void paint(Graphics g) {
   super.paint(g);
   if (drawLine) {
      g.drawLine(0, 100, 100, 10);
   } else if (drawRect) {
      g.drawRect(10, 10, 60, 50);
   } else {
      g.drawOval(10, 10, 50, 50);
   }
}

Upvotes: 2

Your are calling methods from g which is not intialized as your error says : you have only declared it.

Edit : as others have said, your Graphics object is a member of Applet, and is accessible from the method getGraphics. Therefore you can call this method everytime you need it, or create a member in your DrawShapes class.

Graphics g = getGraphics();
public void actionPerformed(ActionEvent ae)
{
    if(ae.getSource()==line)
    {
        g.drawLine(0,100,100,10);
    }
    // etc
}

Upvotes: 0

rgettman
rgettman

Reputation: 178303

You didn't initialize your Graphics reference. You can initialize it by calling the getGraphics() method that Applet inherits from Component.

Graphics g = getGraphics();

Upvotes: 0

Related Questions