3

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

4

1 回答 1

2

上面的问题是 Swing 正在调用您的增量器,并且仅在您的增量功能完成后才执行刷新。相反,您需要启动一个单独的线程来执行此动画并让 Swing 在每次增量后更新。

查看SwingUtilities.invokeLater()SwingWorker类。这是关于 SwingWorker 的教程

于 2012-11-26T11:08:46.040 回答