如何在java graphics2D中旋转后删除原始对象?

时间:2015-10-22 18:12:41

标签: java swing graphics2d

具体来说,我试图只显示旋转的对象。我有一个绘制的矩形,我旋转它。

如何仅显示旋转的矩形并处理旧矩形?

编辑:

以下是旋转矩形的代码:

    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);
        }

这是我从以下地方调用它的paintComponent:

    @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);
    }

1 个答案:

答案 0 :(得分:4)

如果通过覆盖paintComponent(Graphics g)自定义渲染与Graphics对象的形状,请确保使用super.paintComponent(g)作为清除绘图区域的第一行

从那里绘制矩形/旋转矩形

不使用super.paintComponent(g),您之前的绘图(未旋转的矩形)将保持可见

修改

更新源代码:您正在绘制新矩形和旧矩形,因为您的if语句没有else子句

尝试插入一个else子句,以便绘制一个矩形或另一个矩形,目前它可能会绘制一个旋转的矩形,然后绘制未旋转的矩形

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

您可能会或可能不想在其他地方使用rotateClicked = true,因此它会在旋转和未旋转之间来回切换