• Post Reply Bookmark Topic Watch Topic
  • New Topic

ArrayList and object in run method

 
Michael Duff
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In my Java applet I want infinite number of enemys ships to pass from my top left corner and the ships will work like space invaders (ie come closer when hitting the side of applet). But I'm stuck on implementing the feat where infinite amount of ships would arrive in a set interval. The ship objects are added to an ArrayList, but I don't know how to achieve my goal in a correct way The following code causes certain amount of ships to appear but they slowly melt into eachother after each row jump, and they aren't arriving continously. Anyone could give me some hints?



Edit: following code in another method would provide the same result. What I want is continuous flow of enemyships from a side, not having them all appear at start (which these codes do).

 
Mike Pukuotukas
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your infinite loop do not cooperate with GUI properly. If you run it in Swing thread, it blocks the all repaints (as you have taken away the thread that is responsible for repaints). If it is a separate thread, Swing does not get notified that there are some new ships that must be repainted now.

The proposed solution could be to register javax.Swing.timer that would fire periodically action events in the Swing thread (it works similar way as if somebody would be pressing a button periodically). In the action listener you can attach to this timer you can create one ship at time and then call repaint() to show it. The source code of such applet that can be found here (runs here).

 
Michael Duff
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I figured out a solution, by introducing a counter variable I can create an object of my Ship class every second (every 10 ms the counter grows by 1, and when it reaches 100 the counter resets, meaning every second). I don't know if this is elegant but it works like I wanted it to!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!