Friday, May 27, 2011

Creating 2-Dimensional Shapes

In the previous chapters, we learnt how to create an empty frame and also writing out some stuff on it. The next step in creating UI components with Swing is to start drawing 2 dimensional shapes like lines, rectangles, circles and so on. This is what we are going to learn in this chapter.

So, lets get started!!!

Drawing 2 Dimensional Shapes:

Starting with Java 1.0, the Graphics class had methods to draw lines, rectangles, ellipses, and so on. But those drawing operations are very limited. For example, you cannot vary the line thickness and you cannot rotate the shapes.

Java SE 1.2 introduced the Java 2D library, which implements a powerful set of graphical operations. In this chapter, we will only look at the basics of the Java 2D library. The advanced features will be covered subsequently in one of the future chapters.
To draw shapes in the Java 2D library, you need to obtain an object of the Graphics2D class. This class is a subclass of the Graphics class. Ever since Java SE 2, methods such as paintComponent automatically receive an object of the Graphics2D class. Simply use a cast, as follows:

public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
. . .
}

The Java 2D library organizes geometric shapes in an object-oriented fashion. In particular, there are classes to represent lines, rectangles, and ellipses:

Line2D
Rectangle2D
Ellipse2D

These classes all implement the Shape interface.

How to Draw a 2D Shape?

To draw a shape, you first create an object of a class that implements the Shape interface and then call the draw method of the Graphics2D class. For example:

Rectangle2D rect = . . .;
g2.draw(rect);

Using the Java 2D shape classes introduces some complexity. Unlike the 1.0 draw methods, which used integer pixel coordinates, the Java 2D shapes use floating-point coordinates. In many cases, that is a great convenience because it allows you to specify your shapes in coordinates that are meaningful to you (such as millimeters or inches) and then translate them to pixels. The Java 2D library uses single-precision float quantities for many of its internal floating-point calculations. Single precision is sufficient in most cases; after all, the ultimate purpose of the geometric computations is to set pixels on the screen or printer. As long as any roundoff errors stay within one pixel, the visual outcome is not affected. To add on, float computations are faster on some platforms, and float values require half the storage of double values.

However, manipulating float values is sometimes inconvenient for the programmer because the Java programming language is adamant about requiring casts when converting double values into float values. For example, consider the following statement:

float f = 1.2; // Error

This statement does not compile because the constant 1.2 has type double, and the compiler becomes conscious about loss of precision and starts to complain. The solution is to add an F suffix to the floating-point constant:

float f = 1.2F; // Ok

This will tell the complier something like “Hey I know what I am doing, I have explicitly casted this number to a float, so don't complain and carry on with the compilation”

Lets say you do something like below:
Rectangle2D r = . . .
float f = r.getWidth(); // Error

This statement does not compile either and you receive an error. This is because, the getWidth method returns a double and the compiler is having the same problem it had a few lines before. This time, the solution is to provide an explicit cast:
float f = (float) r.getWidth();

Because the suffixes and casts are a bit of a pain, the designers of the 2D library decided to supply two versions of each shape class: one with float coordinates for conscious programmers, and one with double coordinates for the lazy ones (like you and me).

The Rectangle2D Class:
The Rectangle2D class is an abstract class with two concrete subclasses, which are also static inner classes:
Rectangle2D.Float
Rectangle2D.Double

The below image shows the inheritance diagram of this class.



It is best to try to ignore the fact that the two concrete classes are static inner classes. That is just done to avoid names such as FloatRectangle2D and DoubleRectangle2D.
When you construct a Rectangle2D.Float object, you supply the coordinates as float numbers. For a Rectangle2D.Double object, you supply them as double numbers.

For Ex:

Rectangle2D.Float floatRect = new Rectangle2D.Float(10.0F, 25.0F, 22.5F, 20.0F);
Rectangle2D.Double doubleRect = new Rectangle2D.Double(10.0, 25.0, 22.5, 20.0);


Actually, because both Rectangle2D.Float and Rectangle2D.Double extend the common Rectangle2D class and the methods in the subclasses simply override methods in the Rectangle2D superclass. Therefore, there is no benefit in remembering the exact shape type. You can simply use Rectangle2D variables to hold the rectangle references like below instead of our previous example.

Rectangle2D floatRect = new Rectangle2D.Float(10.0F, 25.0F, 22.5F, 20.0F);
Rectangle2D doubleRect = new Rectangle2D.Double(10.0, 25.0, 22.5, 20.0);

The construction parameters denote the top-left corner, width, and height of the rectangle.
The Rectangle2D methods use double parameters and return values. For example, the getWidth method returns a double value, even if the width is stored as a float in a Rectangle2D.Float object.

What we just discussed for the Rectangle2D classes holds for the other shape classes as well.

Creating a Point (Dot):
There is a Point2D class with subclasses Point2D.Float and Point2D.Double. (Just like the Rectangle class)

Below is how you can make a point object:
Point2D p = new Point2D.Double(10, 20);

Drawing Ellipses

The classes Rectangle2D and Ellipse2D both inherit from the common superclass RectangularShape. Even though, ellipses are not rectangular, they do have a bounding rectangle. Look at the image below:

As you can see, the ellipse would fit in properly inside a rectangle.

The RectangularShape class defines over 20 methods that are common to these shapes, among them such useful methods as getWidth, getHeight, getCenterX, and getCenterY.

Rectangle2D and Ellipse2D objects are simple to construct. You need to specify
• The x- and y-coordinates of the top-left corner; and
• The width and height.
For ellipses, these refer to the bounding rectangle. For example,

Ellipse2D e = new Ellipse2D.Double(150, 200, 100, 50);

The line of code above constructs an ellipse that is bounded by a rectangle with the top-left corner at (150, 200), width 100, and height 50.

However, sometimes you don’t have the top-left corner readily available. It is quite common to have two diagonal corner points of a rectangle, but perhaps they aren’t the top-left and bottom-right corners. You can’t simply construct a rectangle as

Rectangle2D rect = new Rectangle2D.Double(px, py, qx - px, qy - py); // Error


If p isn’t the top-left corner, one or both of the coordinate differences will be negative and the rectangle will come out empty. In that case, first create a blank rectangle and use the setFrameFromDiagonal method, as follows:

Rectangle2D rect = new Rectangle2D.Double();
rect.setFrameFromDiagonal(px, py, qx, qy);

Or, even better, if you know the corner points as Point2D objects p and q, then
rect.setFrameFromDiagonal(p, q);

When constructing an ellipse, you usually know the center, width, and height, and not the corner points of the bounding rectangle (which don’t even lie on the ellipse). The setFrameFromCenter method uses the center point, but it still requires one of the four corner points. Thus, you will usually end up constructing an ellipse as follows:

Ellipse2D ellipse = new Ellipse2D.Double(centerX - width / 2, centerY - height / 2, width, height);


Drawing Lines:

To construct a line, you supply the start and end points, either as Point2D objects or as pairs of numbers:

Line2D line = new Line2D.Double(start, end);

or

Line2D line = new Line2D.Double(startX, startY, endX, endY);


A Sample Program incorporating all the shapes we learnt:

Let us wrap up this chapter, with a sample program that will draw all the shapes we just saw in the preceding paragraphs.

Code:

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

/**
* @version 1.0 25-May-2011
* @author Anand Vijayakumar
*/
public class TestShapes
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
CreateFrame frame = new CreateFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}

/**
* A frame that contains a panel with drawings
*/
class CreateFrame extends JFrame
{
public CreateFrame()
{
setTitle("DrawTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

// add panel to frame

CreateComponent component = new CreateComponent();
add(component);
}

public static final int DEFAULT_WIDTH = 400;
public static final int DEFAULT_HEIGHT = 400;
}

/**
* A component that displays rectangles and ellipses.
*/
class CreateComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;

// draw a rectangle

double leftX = 100;
double topY = 100;
double width = 200;
double height = 150;

Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height);
g2.draw(rect);

// draw the enclosed ellipse

Ellipse2D ellipse = new Ellipse2D.Double();
ellipse.setFrame(rect);
g2.draw(ellipse);

// draw a diagonal line

g2.draw(new Line2D.Double(leftX, topY, leftX + width, topY + height));

// draw a circle with the same center

double centerX = rect.getCenterX();
double centerY = rect.getCenterY();
double radius = 150;

Ellipse2D circle = new Ellipse2D.Double();
circle.setFrameFromCenter(centerX, centerY, centerX + radius, centerY + radius);
g2.draw(circle);
}
}

If you run the code above, you will see a frame that looks like below:




Prev: Displaying Text in a Component

Next: Using Colors

No comments:

Post a Comment

© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers