Java examples for 2D Graphics:Rectangle
Draws a rectangle at the specified location with the supplied pen thickness.
//package com.java2s; import java.awt.*; public class Main { /** Draws a rectangle at the specified location * with the supplied pen thickness. left/top are * the <B>center</B> of the lines drawn. Ie * width/height are from the center of one side * to the center of the other. So the inside * width/heights are really lineWidth less than * the values of width and height./*from w ww . j a v a 2 s .c o m*/ * * @param g The Graphics object. * @param left Center of left side edge. * @param top Center of the top edge. * @param width Distance from center of L side to * center of R side. * @param height Distance from center of top side to * center of bottom side. * @param lineWidth Pen thickness. */ public static void drawRect(Graphics g, int left, int top, int width, int height, int lineWidth) { left = left - lineWidth / 2; top = top - lineWidth / 2; width = width + lineWidth; height = height + lineWidth; for (int i = 0; i < lineWidth; i++) { g.drawRect(left, top, width, height); left = left + 1; top = top + 1; width = width - 2; height = height - 2; } } /** Draws a rectangle at the specified location * with the supplied pen thickness and color. * left/top are the <B>center</B> of the lines drawn. * Ie width/height are from the center of one side * to the center of the other. So the inside * width/heights are really lineWidth less than * the values of width and height. * * @param g The Graphics object. * @param left Center of left side edge. * @param top Center of the top edge. * @param width Distance from center of L side to * center of R side. * @param height Distance from center of top side to * center of bottom side. * @param lineWidth Pen thickness. * @param c The color in which to draw. */ public static void drawRect(Graphics g, int left, int top, int width, int height, int lineWidth, Color c) { Color origColor = g.getColor(); g.setColor(c); drawRect(g, left, top, width, height, lineWidth); g.setColor(origColor); } /** Draws a 1-pixel thick rectangle at the specified * location with the supplied color. * * @param g The Graphics object. * @param left The x-coordinate of left side edge. * @param top The y-coordinate of the top edge. * @param width width of rectangle. * @param height height of rectangle. * @param c The color in which to draw. */ public static void drawRect(Graphics g, int left, int top, int width, int height, Color c) { drawRect(g, left, top, width, height, 1, c); } }