 |
|
|
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[] = {100, 150, 170, 160, 130};
int ypoints[] = {100, 80, 120, 150, 160};
public MyShapes()
{
super("MyShapes");
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setSize(300, 300);
addMouseListener( this );
//init shapes
circle = new Ellipse2D.Double( 50, 50, 40, 40 );
polygon = new Polygon( xpoints, ypoints, xpoints.length );
rectangle = new Rectangle( 200, 200, 50, 50 );
show();
}
public void paint( Graphics g )
{
//use Graphics2D
Graphics2D g2d = (Graphics2D)g;
//draw the objects based on the contained values
g2d.fill( circle );
g2d.fill( polygon );
g2d.fill( rectangle );
}
//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.
if( circle.contains( p ) )
{
System.out.println("The circle was hit");
}
if( polygon.contains( p ) )
{
System.out.println("The polygon was hit");
}
if( rectangle.contains( p ) )
{
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();
}
}
|
|
|
 |