Start Search Contents Index Links About
MyShapes.java
/*
 * Author: Havard Rast Blok
 * E-mail: 
 * Web   : www.rememberjava.com
 */

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;

/*
 * Draws a circle, polygon and rectangle using Graphics2D
 */
public class MyShapes extends JFrame implements MouseListener
{
  Ellipse2D.Double circle;
  Polygon polygon;
  Rectangle rectangle;
  int xpoints[] {100150170160130};
  int ypoints[] {100,  80120150160};

  public MyShapes()
  {
    super("MyShapes");
    setDefaultCloseOperationJFrame.EXIT_ON_CLOSE );
    setSize(300300);
    addMouseListenerthis );

    //init shapes
    circle = new   Ellipse2D.Double50504040 );
    polygon = new Polygonxpoints, ypoints, xpoints.length );
    rectangle = new Rectangle2002005050 );

    show();
  }

  public void paintGraphics g )
  {
    //use Graphics2D
    Graphics2D g2d = (Graphics2D)g;

    //draw the objects based on the contained values
    g2d.fillcircle );
    g2d.fillpolygon );
    g2d.fillrectangle );

  }

 //methods from MouseListener

  public void mouseClicked(MouseEvent e)
  {
    Point p;

    /* Note that if you move the mouse while clicking, 
     * it is not registered as a click but a drag.
     * To some users, this might seem a bit too sensitive.
     * So to solve this, move this code to the mouseReleased method.
     */

    //get the point that was clicked
    p = e.getPoint();

    //check which object was clicked
    //if-else is deliberately avoided, so overlapping figures may be detected.
    ifcircle.contains) )
    {
      System.out.println("The circle was hit");
    }

    ifpolygon.contains) )
    {
      System.out.println("The polygon was hit");
    }

    ifrectangle.contains) )
    {
      System.out.println("The rectangle was hit");
    }
    
  }


  public void mouseEntered(MouseEvent e)
  {
  }


  public void mouseExited(MouseEvent e)
  {
  }


  public void mousePressed(MouseEvent e)
  {
  }


  public void mouseReleased(MouseEvent e)
  {
  }


  public static void main(String args[])
  {
    new MyShapes();
  }
}


site: Håvard Rast Blok
mail:
updated: 27 July 2007