Home  >  Q&A  >  body text

java - 多线程控制图片移动

帮忙看下为什么图片没有显示 图片目录在src 下的image 文件夹中

package com.thread;

import java.awt.EventQueue;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class SleepDemo extends JFrame implements Runnable {
private JLabel car;
public SleepDemo(){
    super();
    setResizable(false);
    getContentPane().setLayout(null);
    setBounds(500,300, 300, 96);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    car=new JLabel();
    ImageIcon icon =new ImageIcon(getClass().getResource("/image/1.png"));
    car.setIcon(icon);
    car.setBounds(0, 0, icon.getIconHeight(), icon.getIconWidth());
    getContentPane().add(car);
}
    public void run() {
     int width=getWidth();
     while(true){
         for(int i=0;i<width;i+=3){
             try {
                Thread.sleep(30);
            } catch (InterruptedException e) {
            e.printStackTrace();
            }
             car.setLocation(i,car.getLocation().y);
         }
     }
    }
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try{
                SleepDemo demo=new SleepDemo();
                demo.setVisible(true);    
                new Thread(demo).start();
                System.out.println("线程启动");
                }catch(Exception e){
                e.printStackTrace();
            }            
        }
    });
}
}
PHPzPHPz2713 days ago1254

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 17:56:14

    ImageIcon icon =new ImageIcon(getClass().getResource("/image/1.png"));
    Try changing the file path to a disk path. Testing is OK

    reply
    0
  • Cancelreply