Java Exceptions  «Prev 

Student Project source code


Here is the applet:
The runtime is throwing a java.lang.NullPointerException. We definitely do not want this to occur.
The reason this happens is because of the method makeShape(), and because there is no error checking in the call to makeShape().
Both these sections of the code are highlighted in bold below.

import java.applet.Applet;
import java.util.*;
import java.awt.*;
import java.awt.event.*;

public class Draw extends Applet implements MouseListener{
  Vector drawnShapes = new Vector();
  TextField tf;
  CheckboxGroup group = new CheckboxGroup();

  public void init() {
    Checkbox checkbox;
    setLayout(new BorderLayout());

    tf = new TextField(15);
    add("North", tf);

    Panel p = new Panel();

    checkbox = new Checkbox(null, group, true);
    checkbox.setBackground(Color.red);
    p.add(checkbox);

    checkbox = new Checkbox(null, group, false);
    checkbox.setBackground(Color.blue);
    p.add(checkbox);

    checkbox = new Checkbox(null, group, false);
    checkbox.setBackground(Color.green);
    p.add(checkbox);

    add("South", p);
    addMouseListener(this);
  }
  

  Shape makeShape() {
    Shape s = null;

    String shapeString = tf.getText();
    if (shapeString.equals("Circle"))
      s = new Circle();
    else if (shapeString.equals("Square"))
      s = new Square();

    return s;
  }
  
  public void mousePressed(MouseEvent mouse_evt) {
     int x = mouse_evt.getX();
     int y = mouse_evt.getY();

     Checkbox checkbox;
     Shape s;

     s = makeShape();  
     checkbox = group.getSelectedCheckbox();
     s.color = checkbox.getBackground();

     s.x = x;
     s.y = y;

     drawnShapes.addElement(s);
     repaint();

  } // end mousePressed

   // other methods for MouseListener
  public void mouseClicked(MouseEvent mouse_evt){
  }

  public void mouseEntered(MouseEvent mouse_evt){
  }

  public void mouseExited(MouseEvent mouse_evt){
  }

  public void mouseReleased(MouseEvent mouse_evt){
  }

   public void paint(Graphics g) {

     Shape s;
     Enumeration e = drawnShapes.elements();

     while (e.hasMoreElements()) {
       s = (Shape)e.nextElement();
       s.draw(g);
     }
   } // end paint
} // end Draw

abstract class Shape {
   Color color;
   int x;
   int y;
   int width = 20;

   abstract void draw(Graphics g);
}
class Circle extends Shape {
   void draw(Graphics g) {
      g.setColor(this.color);
      g.fillOval(x, y, width, width);
   }
}

class Square extends Shape {
   void draw(Graphics g) {
      g.setColor(this.color);
      g.fillRect(x, y, width, width);
   }
}