Runnable接口可以让线程更加灵活。
以下案例实现图片的移动,思路:通过label的x位置变化,实现图片移动
public class Demo extends JFrame { private JLabel label = new JLabel(); private static Thread t; private int count = 0; private Container c = getContentPane(); public Demo() { setBounds(300, 200, 250, 100);//窗体位置、大小 setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); c.setLayout(null); URL url = Demo.class.getResource("1.gif");//图片地址 Icon icon = new ImageIcon(url);//实例化icon label.setIcon(icon);//将图放入标签中 label.setHorizontalAlignment(SwingConstants.LEFT);//label内部左布局,即图片在label左侧 label.setBounds(0, 10, 50, 50); //label.setBorder(BorderFactory.createLineBorder(Color.RED));//边框颜色 c.add(label); t = new Thread(new Roll());//调用Roll线程 t.start();//启动 setVisible(true); } class Roll implements Runnable {//定义Roll内部类,实现Runnable接口 public void run() { while (count <= 200) { label.setBounds(count, 10, 50, 50);//label位置 try { Thread.sleep(1000);//休眠1s } catch (InterruptedException e) { e.printStackTrace(); } count += 4;//步进距离4 if (count >= 200) {//如果到右端,重新从左端开始 count = 0; } } } } public static void main(String[] args) { new Demo();//实例化窗体 } }