Search code examples
javaswinggraphicsdisposegraphics2d

Disposing Graphics2D drawing after it is drawn


For a game that I'm working on I need to draw a rectangle that gets smaller and smaller. I have figured out how to draw the rectangle smaller by using a swing Timer like this:

    timer = new Timer(100, new ActionListener(){
        public void actionPerformed(ActionEvent e){
            Graphics2D g2d = (Graphics2D) panel.getGraphics();
            if(width > 64){
                g2d.drawRect(x,y,width,height);
                x += 1;
                y += 1;
                width -= 1;
                height -= 1;
            }
        }
    });
    timer.start();

The problem I am having is that it wont remove the rectangle that was drawn before so it wont look like it's shrinking but more like it's filling in. So how would I remove the previously drawn rectangle right after the smaller rectangle have been drawn?


Solution

  • You might start with:-

    Change:

    Graphics2D g2d = (Graphics2D) panel.getGraphics(); 
    

    to:

    repaint();
    

    The Graphics instance from getGraphics() is transient, the window might be repainted whenever the JVM feels it is necessary.

    The overridden method might look like this.

        @Override
        public void paintComponent(Graphics g){
            super.paintComponent(g);  // Effectively clears the BG
            Graphics2D g2d = (Graphics2D)g;
            if(width > 64){
                g2d.drawRect(x,y,width,height);
                x += 1;
                y += 1;
                width -= 1;
                height -= 1;
            }
            // Toolkit.getDefaultToolkit().sync(); 
            // g2d.dispose();  NO!  Don't dispose of this graphics instance
        }