Draw rectangle border thickness
Asked Answered
M

3

30

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

Mccann answered 18/11, 2010 at 20:56 Comment(0)
O
51

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;
Ogburn answered 18/11, 2010 at 20:59 Comment(2)
Do I have to unset the strokeMccann
@JPC, yes. The stroke will then stay thicker. I will add code that addresses that issue. Stand by.Ogburn
S
1

Here's how to do this : Border with colored line with thickness 5.

Border linebor = BorderFactory.createLineBorder(new Color(0xAD85FF), 5);
Shelburne answered 30/1, 2013 at 15:35 Comment(1)
Does not answer the question.Englut
B
0
**Tested code with buffered image with different thickness values**:

Graphics2D g = bufferedImage.createGraphics();

int height = //image height

int width = //image height

int borderWidth = //border thickness

int borderControl = 1;

//set border color

g.setColor(Color.BLACK);

//set border thickness

g.setStroke(new BasicStroke(borderWidth));

//to fix issue for even numbers

if(borderWidth%2 == 0){

borderControl = 0;

}

g.drawLine(0, 0, 0, height);

g.drawLine(0, 0, width, 0);

g.drawLine(0, height – borderControl, width, height – borderControl);

g.drawLine(width – borderControl, height – borderControl, width – borderControl, 0);
Bunnybunow answered 6/12, 2014 at 9:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.