我想实现一个字符串在屏幕上从左到右移动
可是运行结果与预期很不相同,
在线程sleep之后,仍在执行后面的代码!!很是不解
为了清楚,我把sleep的时间调到了10秒
代码即运行结果如下:
import java.awt.*;
import javax.swing.*;
public class TestThread1 extends JPanel{
 int x=0,y=10;
 String st="Q";
 boolean stop=true;
public  void paintComponent(Graphics g){
super.paintComponent(g);
this.setPreferredSize(new Dimension(400, 400));
g.drawString(st,x,y);
mov();
}

void mov()
{
Thread t=new Thread(){
public void run(){
while(stop){
try{
Thread.sleep(10000);
x+=5;
repaint();
System.out.println("x:"+x);
if(x>=300)stop=false;
}catch(Exception e) {e.printStackTrace();} 
}
}
};
t.start();
}

    public static void main (String[] args) {
     JFrame f = new JFrame();   
         TestThread1 tt = new TestThread1(); 
         f.getContentPane().add(tt); 
         f.setSize(400, 400);  
         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
         f.setVisible(true);}  
    
}
--------------------Configuration: <Default>--------------------
x:5  (第1个10秒)x:10
x:15   (第2个10秒)x:20
x:25
x:30
x:35    (第3个10秒)x:40
x:45
x:50
x:55
x:60
x:65
x:70     (第4个10秒)x:75
x:80
x:85
x:90
x:95
x:100
x:105
x:110
x:115     (第5个10秒)x:120
x:125
x:130
x:135
x:140
x:145
x:150
x:155
x:160
x:165
x:170    (第6个10秒)x:175
x:180
x:185
x:190
x:195
x:200
x:205
x:210
x:215
x:220
x:225
x:230
x:235   (第7个10秒)x:240
x:245
x:250
x:255
x:260
x:265
x:270
x:275
x:280
x:285
x:290
x:295
x:300
x:305
x:310    (第8个10秒)x:315
x:320
x:325
x:330
x:335
x:340
x:345
x:350
x:355
x:360
x:365
x:370     (第9个10秒)
Process completed.

解决方案 »

  1.   

    并不是没有sleep,而是repaint方法在作怪【把它注释掉看看效果】。具体看看repaint方法的执行特性。
      

  2.   

    刚没看代码,看了一下代码发现public  void paintComponent(Graphics g){ 
    super.paintComponent(g); 
    this.setPreferredSize(new Dimension(400, 400)); 
    g.drawString(st,x,y); 
    mov(); 
    } 你的repait会调用paintComponent,paintComponent又会调用mov(),mov()又会起一个线程。所以你的程序启动了许多的线程。
    把mov方法改为:
     boolean isMoved=true;public  void paintComponent(Graphics g){ 
    super.paintComponent(g); 
    this.setPreferredSize(new Dimension(400, 400)); 
    g.drawString(st,x,y); 
    if(isMoved)
    {
    mov();
    isMoved=false;


      

  3.   

    另一个的办法是public  void paintComponent(Graphics g){  
    super.paintComponent(g);  
    this.setPreferredSize(new Dimension(400, 400));  
    g.drawString(st,x,y);  
    //mov();              注释掉,移到构造函数里
    }  public  TestThread1(){
            mov();
            }