I would like display different pictures in a JFrame (in a random order). I am using Threads in the application as the display will need to be constantly updated.
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);
}
}
}
}
and
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);
}
(each of the car# classes extends the Cars class so i can override things later)
What i Tried to do was create a multidimensional array (genmap()) which was filled with random numbers (which works fine(also is there a way i can only run this once in the thread?)), these random numbers would correlate to the car id. Then display thee corresponding car picture to the screen using the ID, this is where I am stuck.
I have tried various ways but it usually turns out that ‘pic’ needs to be static (which it can’t be, otherwise it would only show car4’s image)
I know i could use if statements, but would really like to use the id directly, so it is easy to add new cars later on(just make the new object in the Cars class), does anybody have any idea?
I’m not going to go through your code in detail – the general approach should be:
javax.swing.Timerto update the picture periodicallyRandom.nextInt(n+1)to choose a picture from a set ofnpictures