Java Reference
In-Depth Information
This method is frequently used in association with the contains() method to test efficiently whether
the cursor lies within a particular shape. Testing whether the cursor is within the enclosing rectangle will
be a lot faster in general than testing whether it is within the precise boundary of the shape, and is good
enough for many purposes - when selecting a particular shape on the screen to manipulate it in some
way for instance.
There are also versions of the contains() m ethod to test whether a given rectangle lies within the
area occupied by a rectangle object - this obviously enables you to test whether a shape lies within
another shape. The given rectangle can be passed to the contains() method as the coordinates of its
top-left corner and its height and width as type double , or as a Rectangle2D reference. The method
returns true if the rectangle object completely contains the given rectangle.
Let's try drawing a few simple lines and rectangles by inserting some code in the paint() method for
the view in Sketcher.
Try It Out - Drawing Lines and Rectangles
Begin by adding an import statement to SketchView.java for the java.awt.geom package:
import java.awt.geom.*;
Now replace the previous code in the paint() method in the SketchView class with the following:
public void paint(Graphics g) {
// Temporary code
Graphics2D g2D = (Graphics2D)g; // Get a Java 2D device context
g2D.setPaint(Color.RED); // Draw in red
// Position width and height of first rectangle
Point2D.Float p1 = new Point2D.Float(50.0f, 10.0f);
float width1 = 60;
float height1 = 80;
// Create and draw the first rectangle
Rectangle2D.Float rect = new Rectangle2D.Float(p1.x, p1.y, width1, height1);
g2D.draw(rect);
// Position width and height of second rectangle
Point2D.Float p2 = new Point2D.Float(150.0f, 100.0f);
float width2 = width1 + 30;
float height2 = height1 + 40;
// Create and draw the second rectangle
g2D.draw(new Rectangle2D.Float(
(float)(p2.getX()), (float)(p2.getY()), width2, height2));
g2D.setPaint(Color.BLUE); // Draw in blue
// Draw lines to join corresponding corners of the rectangles
Line2D.Float line = new Line2D.Float(p1,p2);
Search WWH ::




Custom Search