使用Thread类可以实现并发线程,但是必须要继承它就无法继承其他类,这不符合实际应用。
于是就有了Runnable接口,他只有一个run方法,使用与线程一样
下面是一个窗体载入图片,图片不停动的例子,笑脸会从左到右运动
package defaul;
import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;
import java.io.IOException;
import java.net.URL;
import java.nio.CharBuffer;
import java.util.concurrent.CountDownLatch;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class T extends JFrame implements Runnable{
private JLabel jLabel = new JLabel();
private int count = 0;
private Container container = getContentPane();
public T(){
setBounds(200,200,500,90);
setDefaultCloseOperation(EXIT_ON_CLOSE);
container.setLayout(null);
// URL url = T.class.getResource("隐藏.png");//当前编译文件的class类寻找图片
Icon icon = new ImageIcon("src/defaul/隐藏.png");
jLabel.setIcon(icon);
jLabel.setVerticalAlignment(SwingConstants.NORTH);
jLabel.setBounds(0,0,500,50);
container.add(jLabel);//使标签可见
setVisible(true);
}
public static void main(String[] args) {
T t = new T();
Thread a = new Thread(t);//参数为接口的实现对象
a.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
count+=10;
if(count>=500){
count = 10;
}
jLabel.setBounds(count,0,500,50);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}