Java Basics  «Prev 

Project Assignment Java Source Code for Drawing Program

Project Assignment Source Code

Here is the source code for the drawing program you will modify.
If you look at how the classes, variables, and methods are defined, you will notice that none of them use access control keywords (except for the applet, which must be defined as public).

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

public classDraw 
extendsApplet implements MouseListener{
 Vector drawnShapes = new Vector();
 Choice shapeChoice;
 CheckboxGroup group = new CheckboxGroup();
public void init() {
   Checkbox checkbox;
   setLayout(new BorderLayout());
   shapeChoice = new Choice();
   shapeChoice.addItem("Circle");
   shapeChoice.addItem("Square");
   add("North", shapeChoice);
   Panel p = new Panel();
   checkbox = new Checkbox(null, group, true);
   checkbox.setBackground(Color.red);
   // add
   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);
 } // end init
 // implements interface MouseListener
public void mousePressed(MouseEvent mouse_evt) {
  int x = mouse_evt.getX();
  int y = mouse_evt.getY();
  Checkbox checkbox;
  Shape s;
  String shapeString = shapeChoice.getSelectedItem();
  checkbox = group.getSelectedCheckbox();
  if (shapeString.equals("Circle"))
   s = new Circle(checkbox.getBackground(), x, y);
  else
   s = new Square(checkbox.getBackground(), x, y);
  checkbox = group.getSelectedCheckbox();
  s.color = checkbox.getBackground();
  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 voidpaint(Graphics g) {
  Shape s;
  Enumeration e = drawnShapes.elements();
  while(e.hasMoreElements()) {
   s = (Shape)e.nextElement();
   s.draw(g);
  }
 } // end paint
} // end Draw
abstract classShape {
  public Color color;
  public int x;
  public int y;
  public int width = 20;
  public abstract void draw(Graphics g);
} // end Shape
classCircle extends Shape {
  public void draw(Graphics g) {
  g.setColor(this.color);
  g.fillOval(x, y, width, width);
 }
} // end Circle
classSquare extends Shape {
  public void draw(Graphics g) {
    g.setColor(this.color);
    g.fillRect(x, y, width, width);
  }
} // end Square