我怎么能暂停一个循环?

时间:2013-10-03 22:59:23

标签: java

我正在制作一个用户可以获得“工作”的游戏,并且总薪水增加了他们的工资,它会暂停一秒钟,然后重复。它就像Cookie Clicker中的cookie系统,你在那里制作一些饼干,它会暂停,然后更多地显示出来。在游戏中,您单击一个按钮就可以获得“工作”。

//The button to get a job
                    JButton workButton = new JButton("Get a job");
                    mainLayout.gridx = -1;
                    mainLayout.gridy = 1;
                    mainPanel.add(workButton, mainLayout); 
                    workButton.addActionListener(new ActionListener(){

                        @Override
                        public void actionPerformed(ActionEvent arg0) {

                            boolean jobButtonClicked = true;
                            Random jobGenerator = new Random();
                            int jobSalary = jobGenerator.nextInt(200);
                            workLabel.setText("You are making $" +jobSalary);
                            int totalMoney = 0;

                            for(jobButtonClicked = true;;){

                                totalMoney = totalMoney + jobSalary;
                                //I want the total Money to increase by jobSalary, 
                                //pause for one second, and then do it again.

                            }


                        }

                });

我希望暂停发生在这里:

for(jobButtonClicked = true;;){

                            totalMoney = totalMoney + jobSalary;
                            //I want the total Money to increase by jobSalary, 
                            //pause for one second, and then do it again.

我尝试了“Thread.sleep();”,但是如果我没有填写参数,我得到错误“Thread类型中的方法sleep(long)不适用于arguments()”。如果我把括号中的毫秒数我得到错误:“未处理的异常类型InterruptedException”我是这个东西的初学者,我这样做是为了学习。如果可以的话请帮忙。谢谢你的时间。

1 个答案:

答案 0 :(得分:1)

try{
    Thread.sleep(1000);
} catch (InterruptedException e){}

不要忘记为循环创建一个新线程。对于休眠的东西使用事件调度线程并不好,因为它会使你的应用程序冻结。

相关问题