Search code examples
javaswinggraphics2d

How to remove original object after rotation in java graphics2D?


Specifically, I am trying to display only the rotated object. I have a drawn rectangle and I rotate it.

How to I display only the rotated rectangle and dispose of the old one?

EDITED:

The following is the code to rotate my rectangle:

    private void rotateRectangle(Graphics g, Rectangle rect, Color c){
            Graphics2D g2d = (Graphics2D) g.create();
            x = rect.x;
            y = rect.y;
            g2d.setColor(c);
            g2d.rotate(Math.PI/6, PANEL_WIDTH/2,PANEL_HEIGHT/2);
            g2d.drawRect(PANEL_WIDTH/2-x/2, PANEL_HEIGHT/2-y/2, x, y);
        }

And this is the paintComponent where I call it from:

    @Override
    public void paintComponent(Graphics g) {        
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setStroke(new BasicStroke(3));

            //these are declared before 
            rect.x = x;
            rect.y = y;

            if(rotateClicked){
                rotateRectangle(g2d,rect,squareColor);
                rotateClicked = false;
            }
            drawRectangle(g2d, rect, squareColor);
            getArea(x,y);
    }

Solution

  • If custom rendering shapes with a Graphics object by overwriting paintComponent(Graphics g), ensure you use super.paintComponent(g) as the first line to clear the drawing area

    From there draw your Rectangle/rotated Rectangle

    Without using super.paintComponent(g), your previous drawings (the unrotated Rectangle) will remain visible

    EDIT

    With the update of source code: you are drawing both the new and the old rectangle because your if statement does not have an else clause

    Try inserting an else clause so that it will draw one rectangle or the other, currently it maybe draws a rotated rectangle and then draws the unrotated rectangle

    if(rotateClicked)
    {
        rotateRectangle(g2d,rect,squareColor);
        rotateClicked = false;
    }
    else
        drawRectangle(g2d, rect, squareColor);
    

    You may or may not want a rotateClicked = true in the else so it will flip back and forth between rotated and unrotated