I am writing a 2d game at the moment to learn java, and i use a thread as a counter to animate the player (it increases an integer, which tells the paintComponent method which picture to paint). But for some reason the thread is executed twice before it sleeps. The relevant thread is the shipanimation thread.
public class Frame extends JFrame implements KeyListener{
public static Frame frame;
private JPanel contentPane;
RenderPanel panel;
public Ship ship = new Ship(36, 72);
int y = 0;
int time;
int animation = 0;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new Frame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Frame() {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new RenderPanel();
setBounds(100, 100, 256*3, 276*3);
ship.setPos((this.getWidth()/2), (this.getHeight()/4)*3);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(0, 0, 0, 0));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
Thread backgr = new Thread("Hintergrund"){
public void run(){
try {
while(true){
if(frame.y < 0){
frame.y = 300;
}
frame.y -= 1;
Thread.sleep(50);
panel.repaint();
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread anim = new Thread("shipanimation"){
public void run(){
try {
while(true){
if(Frame.frame.animation > 7){
Frame.frame.animation = 0;
}else{
Frame.frame.animation++;
}
System.out.println(Frame.frame.animation);
panel.repaint();
Thread.sleep(500);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
backgr.start();
anim.start();
contentPane.add(panel);
panel.setLayout(null);
}
Can anyone tell me why this is happening? The program seems to increase the number twice, and also prints it twice, then sleeps for 500ms and then does the same again.
Edit: Thanks for your tips, so i changed the Code to:
public Frame() {
aTimer = new Timer(400, this);
aTimer.start();
backTimer = new Timer(25, this);
backTimer.start();
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new RenderPanel();
setBounds(100, 100, 256*3, 276*3);
ship.setPos((this.getWidth()/2), (this.getHeight()/4)*3);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(0, 0, 0, 0));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
contentPane.add(panel);
panel.setLayout(null);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == aTimer){
if(Frame.frame.animation > 7){
Frame.frame.animation = 0;
}else{
Frame.frame.animation++;
}
System.out.println(Frame.frame.animation);
panel.repaint();
}
if(e.getSource() == backTimer){
if(frame.y < 0){
frame.y = 300;
}
frame.y -= 1;
panel.repaint();
}
}
But it's still the same, the timer executes everything twice and then waits the time.