我想在JFrame中顯示不同的圖片(以隨機順序)。我在應用程序中使用線程,因爲顯示將需要不斷更新。Java顯示不同的對象
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);
}
(每車#類的擴展了汽車類,所以我可以覆蓋事情以後再說) 什麼我試圖做的就是創建一個多維數組(genmap()),它是隨機數字填寫(這工作正常(也有一種方法,我只能在線程中運行一次?)),這些隨機數字將與車號相關聯。然後使用ID將相應的汽車圖片顯示在屏幕上,這就是我卡住的地方。
我已經嘗試了各種方法,但通常結果是「知情同意」必須是靜態的(這是不可能的,否則只會顯示CAR4形象)
我知道if語句我可以使用,但真的想直接使用id,所以稍後添加新車很容易(只需在Cars類中創建新對象),是否有人有任何想法?
什麼是睡眠(0)的目的是什麼?我會做的是創建一個你所有車輛的列表,將它傳遞給JFRame,然後JFrame隨機選擇列表中的車輛並繪製它們。不知道我明白你的確切目標是什麼。 – 2012-02-29 15:40:19
了不起的代碼!爲什麼不使用容器,首先?你聲明'int [] [] map = new int [Width] [Height];'然後在循環中使用任意整數......等等 – vulkanino 2012-02-29 15:41:12
1)爲了更好地提供幫助,請發佈[SSCCE](http ://sscce.org/)。 2)請爲代碼塊使用一致的邏輯縮進。 3)請爲班級學習常見的[Java命名法](http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#73307)(具體用於名稱的情況)方法和屬性名稱並一致使用它。 – 2012-02-29 16:17:30