Clear window from drawing objects

喜欢而已 提交于 2019-12-08 19:38:32
Hovercraft Full Of Eels

Your problem looks to be that your paint method is not calling the super's paint method since this will have the component clean itself of all "dirty" image bits. But having said that, you shouldn't draw directly in the JFrame. Instead draw in the paintComponent method of a JComponent or JPanel, and in that method be sure to call the super's paintComponent method:

public class MyDrawingPanel extends JPanel {

    @Override
    proteced void paintComponent(Graphics g) {
        super.paintComponent(g); // don't forget this!

        // do your drawing here
    }
}

Also, why does your Draw class, and thus all classes that derive from it, extend JPanel when it is not being used as a JPanel? You are giving a lot of unnecessary overhead to these classes this way.


Edit
You ask:

So you mean I should move Everything in the paint-method to the paintComponent-method in Draw? Why protected?

No. I mean that Draw should not extend JPanel, but instead should be a logical class, not a Swing component-derived class. I think that you should create a new class, say called MyDrawingPanel where you do all of your drawing. Please see my code snippet above. Also paintComponent is declared in JComponent to be protected, not public, and I see no advantage to making it public when overriding it, so I recommend leaving it protected.

Please read the Swing Info Links to see the Swing graphics tutorials and give them a read.


Edit 2
You're also using a getGraphics() call on a component to get your Graphics object, not good as this will return an unstable Graphics object. Instead do all drawing in the paintComponent method or on a BufferedImage (that again is drawn in paintComponent).


Edit 3

Some of my code examples:

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