如何在运行动画时更新jlabel



我有一个小动画,其中一个矩形,它是一个蓝色背景的jlabel,不断地向下移动屏幕。我正在运行一个线程来做到这一点。

现在,我想有另一个jlabel,它显示矩形的当前位置。

public void run() 
{ 
    Pnl.requestFocus();

    x = (int) p.getX(); //find location of rectangle
    y = (int) p.getY();
    while (y < 450) 
    {
        RectangleLabel.setLocation(x, y); //reset location of the rectangle
        y += 10;

        try {
                Thread.sleep(100);
            } 
        catch (InterruptedException e)
        {
            }
    }
}

现在我想把这段代码插入while语句中。

locationLabel.setText(String.valueOf(450-y));

但每次我这样做,jlable更新,但矩形不再移动。

我该怎么做?

Try This:

运行这个例子

   import javax.swing.*;
   import java.lang.*;
class TestThread extends JFrame implements  Runnable{
JLabel RectangleLabel,locationLabel;
int x,y=0;
TestThread()
{
    setVisible(true);
    setLayout(null);
    RectangleLabel=new JLabel("Rectangle");
    RectangleLabel.setBounds(10,10,100,100);
    locationLabel=new JLabel();
    locationLabel.setBounds(200,200,100,100);
    add(RectangleLabel);
    add(locationLabel); 
    setSize(1000,1000);
    Thread t=new Thread(this);
    t.run();
  }
   public void run() 
 { 
while (y < 450) 
{
    RectangleLabel.setLocation(x, y); //reset location of the rectangle
    y += 10;
    locationLabel.setText(""+y);
    try {
            Thread.sleep(100);
        } 
    catch (InterruptedException e)
    {
    }
    if(y==440)
    {
        y=0;
     }
   }
}
 public static void main(String args[]) {
    TestThread t=new TestThread();
  }   
}

最新更新