我想在while循环中使用计时器。也就是说,当while循环体中包含计时器时,我想要多次运行该循环体。然而,每当我这样做的时候,while循环的主体似乎会在计时器触发所需的次数之前执行并递增。它应该在while循环递增之前触发15次,但它似乎在计时器触发所需的次数之前立即通过while循环运行,我不明白这一点。
我知道这对其他任何事情都不是问题,因为当我只运行一次代码(即没有while循环)时,它运行得很好。这个想法是假设每1300ms移除和更换一个JLabel,直到显示15个图像。一旦它显示了15个图像,它就会移动到2D数组的下一行,其中总共有60行。
任何帮助都将不胜感激。我已经把代码放在下面了。
public class Game implements KeyListener, ActionListener{
private Preparation prep;
private Window window;
private JLabel earthLabel;
private JPanel panel;
private Timer timer;
private JLabel[] arrayOfAllSpaceshipsLabels;
private int[] arrayOfAllSpaceshipsIndexes;
private JLabel currentShipLabel;
private int numberOfBlocks;
private int firings;
private int[][] blocks = new int[60][15] //the values in this array have been initalized in another class that is too big and not relevant to my problem
public Game(){
window = new Window("Space Game");
runBlock();
}
private void runBlock() {
int blocksLength = blocks.length;
numberOfBlocks = 0;
while(numberOfBlocks < blocksLength){
firings = 0;
timer = new Timer(1333, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if (firings == 15){
panel.removeAll();
panel.revalidate();
panel.repaint();
timer.stop();
System.out.println("Block finished");
return;
}
panel.removeAll(); /*(currentShipLabel);*/
panel.revalidate();
panel.repaint();
currentShipLabel = arrayOfAllSpaceshipsLabels[blocks[numberOfBlocks][firings]];
panel.add(currentShipLabel);
panel.validate();
firings++;
}
});
timer.start();
}
numberOfBlocks++;
}
}
public class Window extends JFrame{
private JPanel panel;
public Window(String title){
SwingUtilities.isEventDispatchThread();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//this.setBackground(Color.BLACK);
panel = new JPanel();
this.add(panel);
this.pack();
this.setSize(500,500); //my edit
panel.setBackground(Color.BLACK);
this.setVisible(true);
}
public JPanel getPanel() {
// TODO Auto-generated method stub
return panel;
}
}https://stackoverflow.com/questions/44471960
复制相似问题