Why do my shapes and images disappear on my panel?

老子叫甜甜 提交于 2019-12-12 22:44:30

问题


I have used the paintComponent method to draw shapes on my panel. However, every time I minimize the frame or resize it, they disappear. Not sure what to add to my code.

   public class ShapePanel extends JPanel implements ActionListener, MouseListener{

    int a,b,c,d;
    Graphics2D g2D;
    private Rectangle2D rect = new Rectangle2D(a,b,c-a,d-b);

    public ShapePanel(){

    addMouseListener(this);
    setLayout(new GridLayout());
}

    public void paintComponent(Graphics g) {

    g2D = (Graphics2D) g;
    g2D.draw(rect);
    repaint();

}


   //get methods for coordinates: MousePressed, MouseReleased

回答1:


Don't call repaint() under the paintComponent method. Also, do super.paintComponent(g) the first thing in your paintComponent method.

Update: your code has a lot of compile errors. However, please see below a list of things to change:

  • new Rectangle2D(a, b, c, d) should be new Rectangle2D.Float(10, 10, 100, 100); or anyway, a, b, c and d should have some values, otherwise they are all zero, so no rectangle
  • name the class the same both in definition and in constructor
  • implement mouseClicked, mouseEntered and mouseExited
  • remove g2D.draw() from actionPerformed and don't keep a reference to g2D in the class.

I have the full code that is working if you need it.



来源:https://stackoverflow.com/questions/14478112/why-do-my-shapes-and-images-disappear-on-my-panel

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