Java move jlabel in animation every 0.5 second

2019-02-27 12:31发布

问题:

I want simple animation to set location every 0.5 second but it doesnt animate only set location at the end of the loop.

int x=1;
int y=1;

while(x<100){

jLabel1.setLocation(x, y);

x=x+10;
y=y+10;
try{Thread.sleep(500);}catch(InterruptedException e){}

}

I have tried drawing animation with thread.sleep() and it worked, it was animated correctly but unfortanly that is not option for me as i need to move jlabel around frame wich has figure picture inside it. Can someone pls help me with this problem.

i have tried with this two same result

jLabel1.setBounds(x, y, jLabel1.WIDTH,jLabel1.HEIGHT);  //not working 
jLabel1.move(x,y);  //not working 

回答1:

Instead of using Java Timer try with Swing Timer that is more suitable for Swing application.

Please have a look at How to Use Swing Timers

Find a sample code How to fix animation lags in Java?