图形内容被最大化擦除

时间:2011-09-20 12:45:42

标签: java swing jframe graphics2d

我正在开发一个GUI绘画应用程序。但问题是帧内容在最小化然后最大化时被擦除。我知道问题是什么,它是在最大化之后再次调用paint并且框架的内容未得到正确处理。但即使知道了错误,我也无法解决这个问题。

以下是导致此行为的主要代码:

public void paint(Graphics g) {
    /*From minimized to maximized*/
    System.err.println("Inside paint now ");
   try{
    if(color==colour.red)
        g.setColor(Color.red);
    else if(color==colour.green)
        g.setColor(Color.green);
    else if(color==colour.pink)
        g.setColor(Color.PINK);
    else if(color==colour.cyan)
        g.setColor(Color.CYAN);
    else if(color==colour.magenta)
        g.setColor(Color.MAGENTA);
    else if(color==colour.orange)
        g.setColor(Color.ORANGE);
    else if(color==colour.white)
        g.setColor(Color.white);
    else if(color==colour.black)
        g.setColor(Color.BLACK);
    else if(color==colour.yellow)
    {
        g.setColor(Color.YELLOW);
        System.out.println("Colour selected ");
    }
    else if(stat==state.line)
    {
            Point p=getMousePosition();

            x=p.x;y=p.y;
            System.out.append("In here ");
            System.out.append("the point is "+x+" "+y);
            if(prevx==0 && prevy==0)
            {
                g.drawLine(x, y, x, y);
            //    System.out.append("the point is "+x+" "+y);
            }
            else
            g.drawLine(x, y, prevx, prevy);
            prevx=x;
            prevy=y;
            System.out.println("Line selected ");
    }
    else  if(stat==state.rectangle)
    {
          if(x<prevx)
          {
                x=x+prevx;
                prevx=x-prevx;
                x=x-prevx;
          }
          if(y<prevy)
          {
                y=y+prevy;
                prevy=y-prevy;
                y=y-prevy;
          }
          g.drawRect(prevx,prevy,x-prevx,y-prevy);
          System.out.println("Rectangle selected ");
     }
     else if(stat==state.circle)
     {
            if(x<prevx)
            {
                x=x+prevx;
                prevx=x-prevx;
                x=x-prevx;
            }
            if(y<prevy)
            {
                y=y+prevy;
                prevy=y-prevy;
                y=y-prevy;
            }
            g.drawOval(prevx,prevy,x-prevx,y-prevy);
            System.out.println("Circle selected ");
     }
     else  if(stat==state.ruler)
     {
            g.drawLine(x, y, prevx, prevy);
            System.out.println("Ruler selected ");
     }
     else if(stat==state.eraser)
     {
            g.setColor(getBackground());
            g.fillRect(x-10, y-10, 20, 20);
            System.out.println("Eraser selected ");
     }
     else
     {
           System.out.append("nothing done");
     }
    }
    catch(Exception e)
    {
    }
}

1 个答案:

答案 0 :(得分:1)

我的投票是mkrhrts的评论,当你应该覆盖paint时,你将覆盖paintComponent

覆盖paint是不好的做法,并且您似乎没有执行以下任何操作以确保它不会中断:

  • 致电super.paint()
  • 致电paintComponentpaintBorderpaintChildren

查看documentation for the paint method