Java Draw Round Cornered Rectangles

Java Draw Round Cornered Rectangles

Drawing Rectangles

Java graphics supports 3 types drawing rectangles.

1. Right-angled rectangles
2. Round-cornered rectangles
3. 3-D Rectangles

Java requires width and height of the rectangle and x and y coordinates where rectangle is be drawn. Java does not include a special method, something like drawSquare(), to draw a square. Square can be drawn with rectangle method only by keeping width and height same.

Every closed figure in Java graphics comes with two methods – drawXXX() that draws outline (not filled with some color) figure and fillXXX() that draws filled (solid) figure. The default drawing color is black with white background which can be changed.

Now let us explore the second type, drawing round cornered rectangles.

Drawing Round Cornered Rectangles

Java also supports the drawing of round cornered rectangles apart right-angled rectangles. It takes two parameters extra of bending away from X-axis and Y-axis (amount of rounding).

Following are the supporting methods from java.awt.Graphics class

1. drawRoundRect(int x, int y, int width, int height, int xbend, int ybend);

2. fillRoundRect(int x, int y, int width, int height, int xbend, int ybend);

Observe the syntax of drawRoundRect() method. How it works? First a right-angled rectangle is drawn at 60 and 50 of x and y coordinates and width and height of 150 and 100 pixels. At 60 and 50, the corner is bend 80 degrees towards X-axis and 100 towards Y-axis. That is, the coordinates 60 and 50 lie on the bounded rectangle of the rounded corners.

Java Draw Round Cornered RectanglesJava Draw Round Cornered Rectangles

The frame you get do not close when clicked over the close icon on the title bar of the frame. It requires extra code.

The darker() method of Color class returns another color which is darker still. That is, color clr2 is darker than clr1. fillRoundRect() draws a solid rectangle filled with color clr2. One more method exist, brighter(). Try with this also as follows.

Leave a Reply

Your email address will not be published. Required fields are marked *