Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User defined functions-for loops (JAVA)

Tags:

java

My question is straight. I have made a simple app in neatbeans in which when I click a button the x coordinates of the text say a '@' keeps changing by 20. heres the code:-

int x;

private void wActionPerformed(java.awt.event.ActionEvent evt) 
{                                  
    x=x+20;       
    q.setLocation(x, 0);    
}

this code simply moves the jlabel ( q ) to the right by 20 coordinates each time i click the jbutton ( w ). now what i want is that when i click the button only ONCE then the position of the JLabel should keep increasing its x coordinate by 20 untill it has reached a specific x coordinate say 200. i tried using for loops :-

private void wActionPerformed(java.awt.event.ActionEvent evt)
{
    for(x=0;x<201;x=x+20)
    {
        q.setlocation(x,0);
    }  
}

but with this when I click the button, the jlabel directly moves to 200 x coordinate without stopping after every 20 coordinates...please help.. Regards, Slinger

like image 463
Samarth Avatar asked Jul 31 '26 03:07

Samarth


1 Answers

The problem with the above is that Swing is calling your incrementer and only performing a refresh once your incrementing function has completed. Instead you need to start up a separate thread to perform this animation and let Swing update after each increment.

Check out SwingUtilities.invokeLater() and the SwingWorker class. Here's a tutorial on SwingWorker.

like image 115
Brian Agnew Avatar answered Aug 01 '26 16:08

Brian Agnew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!