首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在while循环中使用计时器

问在while循环中使用计时器
EN

Stack Overflow用户
提问于 2017-06-10 17:54:55
回答 0查看 2.9K关注 0票数 0

我想在while循环中使用计时器。也就是说,当while循环体中包含计时器时,我想要多次运行该循环体。然而,每当我这样做的时候,while循环的主体似乎会在计时器触发所需的次数之前执行并递增。它应该在while循环递增之前触发15次,但它似乎在计时器触发所需的次数之前立即通过while循环运行,我不明白这一点。

我知道这对其他任何事情都不是问题,因为当我只运行一次代码(即没有while循环)时,它运行得很好。这个想法是假设每1300ms移除和更换一个JLabel,直到显示15个图像。一旦它显示了15个图像,它就会移动到2D数组的下一行,其中总共有60行。

任何帮助都将不胜感激。我已经把代码放在下面了。

代码语言:javascript
复制
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;
    }

}
EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44471960

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档