1

How can I move an image based on a timer? I'm trying to get the image to move without any user input but I've done something wrong because I cant get the image to move.

Am I incorrectly calling the method AnimationPanel that I've built to actually move the image? I have a feeling it has something to do with that.

Here's what I've tried so far: The Overloaded Constructor is so that I can call AnimationPanel with ease from this particular class.

public class ClassC extends Component {
    int x; int y;
    BufferedImage img;

    public void paint(Graphics g) {
        g.drawImage(img, x, y, null);
    }

    public ClassC() {
        try {
            img = ImageIO.read(new File("RobotFrame1.png"));
        } catch (IOException e) {
        }
    }

    public ClassC(int x)
    {}

    public Dimension getPreferredSize() {
        if (img == null) {
            return new Dimension(100,100);
        } else {
            return new Dimension(img.getWidth(null)+900, img.getHeight(null)+900);
        }
    }

    public void AnimationPanel() {

        javax.swing.Timer timer = new javax.swing.Timer(20, new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                x++;
                y++;
                repaint();
            }
        });
        timer.start();
    }

    public static void main(String[] args) {

        JFrame f = new JFrame("Load Image Sample");
        f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        f.add(new ClassC());
        f.pack();
        f.setVisible(true);
        ClassC callanimation = new ClassC(1);
        callanimation.AnimationPanel();
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
moonbeamer2234
  • 351
  • 1
  • 3
  • 12

2 Answers2

4

The component that is on the screen is not the component that you are animating...

// Create first instance here...
f.add(new ClassC());
f.pack();
f.setVisible(true);
// Create second instance here...
ClassC callanimation = new ClassC(1);
callanimation.AnimationPanel();

Instead, this will get you started

ClassC callanimation = new ClassC();
callanimation.AnimationPanel();
f.add(callanimation);
f.pack();
f.setVisible(true);

ps- I'd also be very careful, you are mixing frameworks. While AWT and Swing share some parts of the library, they don't always play nice together ;)

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
3
public ClassC(int x)
{

}

why is this empty? what is x for?

f.add(new ClassC()); <-- you created a ClassC() here
f.pack();
f.setVisible(true);
ClassC callanimation = new ClassC(1); <-- you created a new ClassC here

these two are different because you created them again..

try doing:

ClassC callanimation = new ClassC(1);
f.add(callanimantion); 
f.pack();
f.setVisible(true);
callanimation.AnimationPanel();
Francis Fuerte
  • 254
  • 1
  • 9