我现在正在写一个2D游戏来学习java,我使用一个线程作为计数器来动画播放器(它增加了一个整数,它告诉paintComponent方法绘制哪个图片)。但由于某种原因,线程在睡眠前执行了两次。相关的线程是船舶动画线程。
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);
}
谁能告诉我为什么会这样?该程序似乎增加了两次,并打印两次,然后睡眠500ms然后再次相同。
编辑:感谢您的提示,所以我将代码更改为:
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();
}
}
但它仍然相同,计时器执行所有操作两次然后等待时间。