简体   繁体   English

Java Swing计时器的随机时间间隔?

[英]Random Time intervals for Java Swing Timer?

Hello I am trying to generate a Person object at random intervals using java swing timer. 您好,我正在尝试使用Java Swing Timer随机生成一个Person对象。

I am generating a Random Poisson number using a function, and I am planning to use that randomly generated number as a delay to create the next person object. 我正在使用一个函数生成一个随机泊松数,并且我打算使用该随机生成的数作为创建下一个人物对象的延迟。 However, it seems to not be working as everything is being generated only ~1 second from each other, even though the poisson value indicates a 9 second interval. 但是,这似乎不起作用,因为尽管泊松值表示间隔为9秒,但彼此之间仅约1秒钟才生成所有内容。 Here is my attempt at a solution: 这是我尝试的解决方案:

private ActionListener generatePerson = new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
        doSomething();
        updateTimer();
    }

    private void doSomething()
    {
        try {
            newPerson = new person(buildingType,currenttime,totnumoffloors);
            newPerson.setArrivalTime(timeElapsed);
            newPerson.printArrival();
            peopleQueue[newPerson.currentFloor-1]++;
            floorQueue[newPerson.currentFloor-1]++;
            System.out.println("Added a new person to the queue.");
            repaint();
            System.out.println("Done repainting.");
        } catch (IOException ex) {
            System.out.println("Unable to create object!");
        }
    }

    private void updateTimer()
    {
        int lol = 0;
        periodicPerson.stop();
        newPoissonTime = generatePoisson();
        newPoissonTime = (newPoissonTime*1000);
        lol = (int)newPoissonTime;
        System.out.println("NEW POISSON TIME: " + lol);
        periodicPerson.setDelay(lol);
        periodicPerson.restart(); 
    }
};

I multiplied the poisson time by 1000 to convert it to seconds. 我将泊松时间乘以1000,将其转换为秒。

I then generate the initial timer as: 然后,我将初始计时器生成为:

periodicPerson = new Timer((int)generatePoisson()*1000, generatePerson);

I think the problem is when it generates the Poisson, it just uses that as the time interval, or that the delay is simply not working. 我认为问题是当它生成泊松时,只是将其用作时间间隔,或者延迟根本不起作用。

Thank you very much in advance! 提前非常感谢您!

Don't stop() or restart() the Timer. 不要stop()restart()定时器。

Read the API description for the restart() method to find out why that doesn't work. 阅读有关restart()方法的API描述,以了解为什么它不起作用。

Or if you do need to stop/start the Timer, then you will also need to reset the initial delay . 或者,如果确实需要停止/启动计时器,则还需要重置initial delay

I'm not sure the exact solution, I'll let you play a little. 我不确定确切的解决方案,让您玩一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM