Search code examples
javaawtgraphics2d

Java Graphics2D - drawing corners only on a rectangle


With Graphics2D in Java, How would you create a rectangle that only has its corners drawn (as illustrated below) using the drawLine feature within the Graphics2D object?

****                         ****
*                               *
*                               *

             CONTENT

*                               *
*                               *
****                         ****

Solution

  • I have made a function for this:

       public void drawCornerRectangle(Graphics2D g, int x, int y, int width, int height, int cornerLength) {
            //check width, height and cornerLength
            if ((width < 0) || (height < 0) || (cornerLength < 1)) {
                return;
            }
            //check if width or height is 0
            if(width == 0) {
                g.drawLine(x, y, x, y + cornerLength);
                g.drawLine(x, y + height, x, (y + height) - cornerLength);
                return;
            } else if (height == 0) {
                g.drawLine(x, y, x + cornerLength, y);
                g.drawLine(x + width, y, (x + width) - cornerLength, y);
                return;
            }
            //check cornerLength
            if(cornerLength > width/2 && cornerLength > height/2) {
                g.drawRect(x, y, width, height);
            } else {
                //left up corner
                g.drawLine(x, y, x + cornerLength, y);
                g.drawLine(x, y, x, y + cornerLength);
    
                //right up corner
                g.drawLine(x + width, y, (x + width) - cornerLength, y);
                g.drawLine(x + width, y, x + width, y + cornerLength);
    
                //left down corner
                g.drawLine(x, y + height, x + cornerLength, y + height);
                g.drawLine(x, y + height, x, (y + height) - cornerLength);
    
                //right down corner
                g.drawLine(x + width, y + height, (x + width) - cornerLength, y + height);
                g.drawLine(x + width, y + height, x + width, (y + height) - cornerLength);
            }
        } 
    

    how to call:

    //for square:
    drawCornerRectangle(g, 10, 10, 200, 200, 20); //the same width and height
    
    //for rectangle    
    drawCornerRectangle(g, 10, 10, 100, 150, 20);
    

    Hope this helps.