Draw rectangle border thickness

JPC picture JPC · Nov 18, 2010 · Viewed 58k times · Source

Is it possible to do draw a rectangle with a given border thickness in an easy way?

Answer

jjnguy picture jjnguy · Nov 18, 2010

If you are drawing on a Graphics2D object, you can use the setStroke() method:

Graphics2D g2;
double thickness = 2;
Stroke oldStroke = g2.getStroke();
g2.setStroke(new BasicStroke(thickness));
g2.drawRect(x, y, width, height);
g2.setStroke(oldStroke);

If this is being done on a Swing component and you are being passed a Graphics object, you can downcast it to a Graphics2D.

Graphics2D g2 = (Graphics2D) g;