这个标签从左移到右边后返回到原来的位置
import java.awt.Container;import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class TheardTest extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private int count=0;//控制X坐标
private JLabel jl;
private Thread t;
public TheardTest(){
Container con=this.getContentPane();// 容器
jl=new JLabel("我会移动哦");//标签
jl.setHorizontalAlignment(SwingConstants.LEFT);//左对齐
jl.setBounds(10, 20, 70, 20);
con.add(jl);
this.setLayout(null);
this.setVisible(true);
this.setBounds(300, 200, 400, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t=new Thread(new Runnable(){
public void run(){
for(count=10;count<=200;count=+4){
jl.setBounds(count, 20, 70, 20);
try{
Thread.sleep(1000);
}
catch(Exception e){
e.printStackTrace();
}
if(count==200){
count=10;
}
}
}
});
t.start();
}
public static void main(String args[])
{
new TheardTest();
}
}
import java.awt.Container;import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class TheardTest extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private int count=0;//控制X坐标
private JLabel jl;
private Thread t;
public TheardTest(){
Container con=this.getContentPane();// 容器
jl=new JLabel("我会移动哦");//标签
jl.setHorizontalAlignment(SwingConstants.LEFT);//左对齐
jl.setBounds(10, 20, 70, 20);
con.add(jl);
this.setLayout(null);
this.setVisible(true);
this.setBounds(300, 200, 400, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t=new Thread(new Runnable(){
public void run(){
for(count=10;count<=200;count=+4){
jl.setBounds(count, 20, 70, 20);
try{
Thread.sleep(1000);
}
catch(Exception e){
e.printStackTrace();
}
if(count==200){
count=10;
}
}
}
});
t.start();
}
public static void main(String args[])
{
new TheardTest();
}
}
不是for (count = 10; count <= 200; count =+4)这样导致的结果就是count一直是4,因为count=+4跟count=4的效果一样,应该for (count = 10; count <= 200; count +=4)
for (count = 10; count <= 202; count +=4) {
jl.setBounds(count, 20, 70, 20);
System.out.println("count="+count);
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
if (count == 202) {
count = 10;
}
}