package com.suse.thread;
import java.awt.Container;
import java.net.URL;
import javax.swing.*;
public class SwingAndThread extends JFrame {
private JLabel jl=new JLabel();//声明JLabel标签对象
private static Thread t;//这里虽没有引入java.lang.Thread,但是一切类都继承于超类Object,虽然已经指定继承于JFrame,但可以理解为JFrame继承于超类Object
private int x=0;
private Container container=getContentPane();//声明容器
public SwingAndThread(){//构造方法没有返回类型,不能写void 此外构造函数不能白继承
setBounds(360, 10, 666,666);//绝对定位窗体大小与位置
container.setLayout(null);//使窗体不使用任何布局管理器
URL url=SwingAndThread.class.getResource("1.png");//获取图片的url
Icon icon=new ImageIcon(url);//实例化一个Icon
jl.setIcon(icon);//将图标放在标签中
//设置图片在标签的最左方
jl.setHorizontalAlignment(SwingConstants.LEFT);
jl.setBounds(10, 10, 600, 30);
jl.setOpaque(true);
t=new Thread(new Runnable(){//定义匿名内部类,该类实现Runnable接口
public void run(){//重写run方法
while(x<=666){//设置循环条件
//将标签的横坐标用变量表示
jl.setBounds(x, 666, 200, 50);//x y w h
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
x+=4;
if(x>=556){
x=10;
}
}
}
});
t.start();
container.add(jl);
setVisible(true);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
public static void main(String[] args) {
new SwingAndThread();
}
}
多线程实现图片移动
最新推荐文章于 2021-05-10 14:35:39 发布