Java显示不同的对象

时间:2012-02-29 15:33:59

标签: java arrays multithreading object jframe

我想在JFrame中显示不同的图片(以随机顺序)。我在应用程序中使用Threads,因为显示需要不断更新。

   public class CarsMain extends JFrame implements Runnable {
       Random rand = new Random();

    //the main thread
    Thread thread;
    BufferedImage backbuffer;
    Cars cars;
    Car1 car1;
    //set map of the cars array
    private int Width = 10;
    private int Height = 100;
    int[][] map=new int[Width][Height];

    public static void main(String[] args) {
        new CarsMain();
    }    

    public CarsMain() {
        super("Cars");
        setSize(500,400);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        thread = new Thread(this);
        thread.start();

    }



    //thread run event
    public void run() {

        Thread current = Thread.currentThread();

        while (current == thread) {
            try { Thread.sleep(0); }
            catch(InterruptedException e) { e.printStackTrace(); }


           genmap();
        }
    }

       //Fills map[][] with random numbers (id's)
    private void genmap() {

        for (int i = 0; i<10;i++){      
            for (int j = 0; j<20; j++){     
        map[i][j] = rand.nextInt(5);

                }
            }

    }


    //JFrame paint event
    public void paint(Graphics g) {

        g.drawImage(backbuffer, 0, 0, this);
        for (int i = 0;i<600;i+=128){
            for(int j=30; j<500;j+=128){
                          //this is the part i am stuck on
                                // v this is just put here to test that display
                g.drawImage(cars.Car1.getpic(),i, j, this);
            }
        }
    }
}

    public class Cars{

    public  Image pic;
    public int carid;
    public Cars carList[]= new Cars[10];




    public Cars(int i){

        carid = i;

    }

    public Image getpic(){
        return pic;

    }

    public void setpic(Image pic){
        this.pic = pic;
    }

    public int getCarid(int i){
        return Carid;
    }

    public static final Cars car0 =  new car0(1);
    public static final Cars Car1 = new car1(2);
    public static final Cars Car2  = new car2(3);
    public static final Cars Car3 = new car3(4);
    public static final Cars Car4 = new car4(5);

}

(每个汽车#类扩展了Cars类,所以我可以稍后覆盖一些事情) 我试图做的是创建一个多维数组(genmap()),其中填充了随机数(工作正常(也有一种方法,我只能在线程中运行一次?)),这些随机数将与汽车id。然后使用ID向屏幕显示相应的汽车图片,这就是我被困住的地方。

我尝试了各种各样的方法,但通常证明'pic'需要是静态的(它不能,否则它只会显示car4的图像)

我知道我可以使用if语句,但是真的想直接使用id,所以以后很容易添加新车(只需在Cars类中创建新对象),有没有人有任何想法?

2 个答案:

答案 0 :(得分:1)

我不会详细介绍您的代码 - 一般方法应该是:

  • 使用javax.swing.Timer定期更新图片
  • 使用Random.nextInt(n+1)从一组n图片
  • 中选择一张图片
  • 将图片(或只是他们的文件或URL)保存在列表或数组中
    • 根据需要从文件/网址加载所选图片
  • 告诉GUI重新绘制
  • GUI应该获取当前图像并绘制它

答案 1 :(得分:0)

您无法访问尚未创建的图像。 静态元素在启动时创建。但是你的照片是在创建汽车时创建的。

在CarsMain类中创建每辆车,并将它们添加到Cars中的阵列中。然后写一个getter并使用它。

我认为你在这里做的事情非常沮丧。 你的结构太可怕了。