my task is to write an imitation of cockroach races. I have the following classes: Game is the main class, creates a JFrame and accepts an input parameter (the number of tracks, as needed) Window - a class that inherits the JFrame. the frame parameters are set, the objects of the Panel and Cockroach class are created and added to the same frame. cockroaches are added as follows:
for (int i = 0; i < Game.getNumbOfTrack(); i++) { Cockroach cockroach = new Cockroach(y); cockroach.setBackground(Color.WHITE); add(cockroach); } the Panel class is the heir of Jpanel, on this panel are the tracks for cockroaches; the Cockroach class is the heir of the Panel, implements Runnable. class code:
public class Cockroach extends Panel implements Runnable { Random random = new Random(); private Thread thread; private int x = 145; private int y; private Image cockr; public Cockroach(int y) { this.y = y; try { cockr = ImageIO.read(new File("C:\\Users\\Roman-pc\\IdeaProjects\\Races\\images\\Cockroach.gif")); // загрузка картинки с диска } catch (IOException e) { e.printStackTrace(); } thread = new Thread(this, "tarakan"); thread.start(); repaint(); } @Override public void run() { while (this.x < 500) { this.x += 15; try { Thread.sleep(random.nextInt(1000)); } catch (InterruptedException e) { e.printStackTrace(); } this.repaint(); } } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(cockr, this.x, this.y + 15, null); } } each cockroach outwardly is a picture loaded from disk, which should move along its path. each track has its own picture.
the mistake is that only one cockroach is drawn and runs, and it is always on the last track that I have already tried everything, I can’t understand what's wrong. I tried to remove the streams and leave in the class a clean drawing of these cockroaches, but still the same story. I tried to add each cockroach separately (not in a cycle), all the same, only the last one is drawn, what could be wrong? How to make all cockroaches painted? pliz help !! PS I apologize for a lot of text and code, just the first time I try the GUI and the threads