简体   繁体   中英

Random Time intervals for Java Swing Timer?

Hello I am trying to generate a Person object at random intervals using java swing timer.

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. 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.

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.

Read the API description for the restart() method to find out why that doesn't work.

Or if you do need to stop/start the Timer, then you will also need to reset the initial delay .

I'm not sure the exact solution, I'll let you play a little.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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