my final goal for this application is to animate several items in the same JPanel at a different speed using a thread for each item.the first part is done however the items move at the same speed and i have no idea on how to fix this problem.
package javagamestutos; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Toolkit; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JPanel; public class Board extends JPanel implements Runnable { private Star star; private Thread animator; ArrayList<Star> items=new ArrayList<Star>(); public Board() { setBackground(Color.BLACK); setDoubleBuffered(true); star=new Star(25,0,0); Star star2=new Star(50,20,25); items.add(star2); items.add(star); } public void addNotify() { super.addNotify(); animator = new Thread(this); animator.start(); } public void paint(Graphics g) { super.paint(g); Graphics2D g2d = (Graphics2D)g; for (Star s : this.items) { g2d.drawImage(s.starImage, s.x, s.y, this); } Toolkit.getDefaultToolkit().sync(); g.dispose(); } public void run() { while(true){ try { for (Star s : this.items) { s.move(); } repaint(); Thread.sleep(star.delay); } catch (InterruptedException ex) { Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex); } } } } here is the star class wich is the moving item.
package javagamestutos; import java.awt.Image; import javax.swing.ImageIcon; /** * * @author fenec */ public class Star { Image starImage; int x,y; int destinationX=200,destinationY=226; boolean lockY=true; int delay; public Star(int delay,int initialX,int initialY){ ImageIcon ii = new ImageIcon(this.getClass().getResource("star.png")); starImage = ii.getImage(); x=initialX; y=initialY; this.delay=delay; } void moveToX(int destX){ this.x += 1; } boolean validDestinatonX(){ if(this.x==this.destinationX){ this.lockY=false; return true; } else return false; } void moveToY(int destY){ this.y += 1; } boolean validDestinatonY(){ if(this.y==this.destinationY) return true; else return false; } void move(){ if(!this.validDestinatonX() ) x+=1; if(!this.validDestinatonY() && !this.lockY) y+=1; /*if(!this.validDestinatonY()) y+=1; */ } } and here is the skeleton of the animation that extends a JFrame :
package javagamestutos; import javax.swing.JFrame; public class Skeleton extends JFrame { public Skeleton() { add(new Board()); setTitle("Stars"); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(300, 280); setLocationRelativeTo(null); setVisible(true); setResizable(false); } public static void main(String[] args) { new Skeleton(); } } do you have any idea how to achieve my goals?am i using threads proprely? thank you in advance.
