Reputation:
I have been trying to make a java program that shows a circle on the screen. I have three classes:
first ---> initializes the frame and adds the key listener from input.
panel ---> contains the paintComponent method and the method that will move the object across the screen(I even remembered to put repaint(); )
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?
Upvotes: 0
Views: 86
Reputation: 180113
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.
Upvotes: 1