Java graphics repaint problem

寵の児 提交于 2019-12-03 20:23:41

If you forget to call super.paintComponent(g); the background does not get cleared, so the old image will still be visible. And all JButton's and stuff you added, will not be drawn. To fix this, let the panel draw itself first, then you can draw your stuff on top of it.

@Override
protected void paintComponent(Graphics g) {
     super.paintComponent(g);// <-- let panel draw itself
     Graphics2D g2d = (Graphics2D)g;
     for (Shape i : myArr)
     {
        g2d.draw(i);
     }   
  }

This works too (except that it does not draw widgets you added with DrawingPanel.add(..)). It's a dirty hack:

@Override
protected void paintComponent(Graphics g)
     Graphics2D g2d = (Graphics2D)g;
     g2d.setColor(Color.grey);
     g2d.fillRect(0,0,this.getWidth(),this.getHeight()); //<-- clear the background
     for (Shape i : myArr)
     {
        g2d.draw(i);
     }   
  }

In the listener this would be enough.

if (buttonPress.buttonType.equals("Clear"))
{
   myArr.clear();
   repaint();
}

You shouldn't have to call revalidate();.

Try to call super.paintcomponent(g) from the paintcomponent method. And also make sure you are calling the revalidate and repaint method of JPanel.

Try to call repaint(); of your JPanel.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!