1

I have some shapes created by class Rectangle and I want to surround them with a thick border. However the methods drawRect and drawOval form Graphics class create a thin line as the border of the shape. How can I adjust them so as me to able to manipulate the thickness of the border line? If this is not possible or quite effective, what is another way to assign an adjustable border on the shapes? May I need Rectangle2D or Graphics2D?

After that, do you know how I can “round” the angles of the border of a square so as not to be sharp?

arjacsoh
  • 8,932
  • 28
  • 106
  • 166
  • 2
    Use Graphics2D.setStroke before drawing your rectangle and reset it afterwards. See http://stackoverflow.com/questions/4219511/java-drawrect-border-thickness – Usman Saleem Oct 19 '11 at 16:11

3 Answers3

3

To make the border thicker, use Graphics2D.setStroke(...). And to draw "rounded" rectangles, use Graphics.drawRoundRect(...).

mre
  • 43,520
  • 33
  • 120
  • 170
3

Look into Graphics2D strokes:

If a round join in your stroke isn't soft enough, look into RoundRectangle2D.

Michael Brewer-Davis
  • 14,018
  • 5
  • 37
  • 49
0

I implemented custom rounded shape for icons.

1) The thick border can be painted by :

BasicStroke dashed =new BasicStroke(3.0f,BasicStroke.CAP_BUTT,BasicStroke.JOIN_MITER,10.0f);

2) Rounded shape could be painted by:

Ellipse2D.Double circle = new Ellipse2D.Double(x+1, y+1, 14, 14);
Ellipse2D.Double circleBorder = new Ellipse2D.Double(x, y, 15, 15);

All code is here:

public class ColorIcon implements Icon {

private Color color = Color.WHITE;

/**
 * Constructor for implement custom colored icon 
 * @param color - custom parameter for creating colored icon.
 */
public ColorIcon(@Nonnull Color color) {
    this.color = color;
}

/**
 * Default constructor for implement default icon. 
 */
public ColorIcon() {
}

@Override
public void paintIcon(@Nonnull Component c, @Nonnull Graphics g, int x, int y) {
    Graphics2D g2 = (Graphics2D) g;
    RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    BasicStroke dashed =new BasicStroke(3.0f,BasicStroke.CAP_BUTT,BasicStroke.JOIN_MITER,10.0f);
    Ellipse2D.Double circle = new Ellipse2D.Double(x+1, y+1, 14, 14);
    Ellipse2D.Double circleBorder = new Ellipse2D.Double(x, y, 15, 15);
    g2.setColor(getColor());
    g2.setRenderingHints(hints);
    g2.fill(circle);
    Composite oldComposite=g2.getComposite();
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0));        
    g2.setColor(new Color(1,1,1,1));
    g2.setStroke(dashed);
    g2.draw(circleBorder);
    g2.setComposite(oldComposite);
}

@Override
public int getIconWidth() {
    return 15;
}

@Override
public int getIconHeight() {
    return 15;
}

public Color getColor() {
    return color;
}

public void setColor(@Nonnull Color color) {
    this.color = color;
}

}

Tamara Koliada
  • 1,200
  • 2
  • 14
  • 31