日期:2014-05-20  浏览次数:20673 次

Java求解
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Moving extends Frame implements ActionListener,Runnable{

Thread move=null;
boolean run=true;
public int i=0;
int sleeptime;
TextField text_sleep; 
Label label=new Label(" Welcome!");
Button button_start=new Button("启动");
Button button_interrupt=new Button("中断");
public Moving()
{
super("滚动字");
move=new Thread(this);
setLayout(new FlowLayout());
add(button_start);add(button_interrupt);
add(label);
button_start.addActionListener(this);
button_interrupt.addActionListener(this);
Panel panel_sub = new Panel(new FlowLayout(FlowLayout.LEFT)); 
  this.add(panel_sub);
  panel_sub.add(new Label("SleepTime"));
  this.sleeptime = (int)(Math.random()*1000); //产生随机数作为间隔时间
  text_sleep = new TextField(""+sleeptime,5);
  panel_sub.add(text_sleep);
  text_sleep.addActionListener(this);
setSize(200,100);
setLocation(300,300);
pack();
setVisible(true);
addWindowListener(new WindowCloser());
}
public class WindowCloser extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button_start)
{
run=true;
move=new Thread(this);
move.start();
}
if(e.getSource()==button_interrupt)
{
run=false;
}
}
public void run()
{
while(run)
{
i++;
label.setLocation(label.getX()-2*i,label.getY());
try
{
move.sleep(sleeptime);
}
catch(InterruptedException ie){break;}
}
}
public static void main(String[] args) {
Moving t_ex=new Moving();

}

}
请大侠们给我看看, i++;
label.setLocation(label.getX()-2*i,label.getY());
这两条语句,我想实现字幕滚动,但是我现在的的问题就是i++,得到的字幕情况就是一直往左边滚动,回不到开始的位置····这个问题怎么解决啊?我是初学者,很多方法没有掌握,求解啊····

------解决方案--------------------
i++下面加上一句

if(i==100){
i=1;
}
------解决方案--------------------
因为你的label.getX()-2*i随着i不断地增大时,当整个位置小于0的时候就超出左边了,
所以你要在减到0的时候要往回加,这样才会实现来回滚动
if(label.getX()-2*i<0)
{
i=-i;
i--;
}
else
{
i++;
}
 
 label.setLocation(label.getX()-2*i,label.getY());