0
votes

I have been trying to make a java program that shows a circle on the screen. I have three classes:

  1. first ---> initializes the frame and adds the key listener from input.

  2. panel ---> contains the paintComponent method and the method that will move the object across the screen(I even remembered to put repaint(); )

  3. input ---> implements KeyListener and calls the animation method in panel

In the input class I have this if statment:

if (e.getKeyCode() == KeyEvent.VK_D) {
  new panel().animation();
}

here is the animation method inside of the panel class:

public void animation() {
  playerX += 10;
  System.out.println(playerX);
  repaint();
}

when I runthe program, I know the animation method is being ran because it is outputing playerX to the console (it increased evey time like it was supposed to), but the repaint(); command is being ignored! What am I doing wrong?

1
Where is your code for the paint method()? animation() does nothing but updating a variable... - SJuan76
I am trying to comprehend why this question was down voted. I did a very thorough explanation of my problem. - user4196492

1 Answers

1
votes

Your KeyListener is creating a new panel every time it receives a VK_D event, and invoking animation() on that. That is unlikely to be what you want. It should probably be invoking animation() always on the same panel object, that panel being a visible component in the application UI.