#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    22
    Rep Power
    0

    Problem while creating an animation.


    Hello there. I am having a problem with a custom animation of mine. The purpose of my program is to create a Rectangle on the left part of my screen and make it move all across the way(Towards the right part of my screen) like an animation. The problem is that when I am repainting, the previous rectangle doesnt disappear which results the shapes stacking on top of each other. Here's the code.
    Code:
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.Timer;
    public class Animation2 extends JFrame implements ActionListener {
        JPanel a = new JPanel();
        int x=0,PosX=2;
        Timer tm= new Timer(5,this);
    public Animation2(String name)
            
            {
                super(name);
                setLayout(new GridLayout(1,1));
                setDefaultCloseOperation(EXIT_ON_CLOSE);
                setSize(400,400);
                add(a);
                setVisible(true);
            }
    public void paint(Graphics g)
        {
            
            g.setColor(Color.red);
            g.drawRect(x,30,50,50);
            tm.start();
        }
    public void actionPerformed(ActionEvent e)
        {
     // This part here is to make the rectangle go backwards too.
            if(x>350 || x<00)
            {
                PosX=-PosX;
            }
                    x=x+PosX;
            repaint();
        }
        public static void main(String[] args) {
            Animation2 ok= new Animation2("Test");
            
        }
    }
  2. #2
  3. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,711
    Rep Power
    347
    Try calling the super.paint method to clear the window.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    22
    Rep Power
    0
    Originally Posted by NormR
    Try calling the super.paint method to clear the window.
    Well it worked :O. Can you please explain me the reason behind it? I am a Computer Science student so I want to know .
  6. #4
  7. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,711
    Rep Power
    347
    See the API doc for the paint() method in the Component class
    and follow the "painting" link at the bottom.
    Last edited by NormR; February 23rd, 2014 at 08:57 AM.
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    22
    Rep Power
    0
    Thank you for the assistance. This can be locked now.

IMN logo majestic logo threadwatch logo seochat tools logo