Dylan Reichstadt
Dylan Reichstadt

Reputation: 13

Adding a delay in code execution

I've been spending quite a lot of time researching both the Thread.sleep and Timerfunctions. Essentially I am writing a mortgage loan calculator that is supposed to simulate a few seconds while it calculates. Ideally I want a message to appear saying "Calculating..." and then it will set the results window to visible after a second or two.

Thread.sleep seems to ignore its position in the code, so my setText for "Calculating..." never finishes. This is what brought me upon Timer.

Timer seems to partially work, but it doesn't create a halt in running the code until the timer completes... It moves onto the following lines.

Any help? Attaching a chunk of my code.

ActionListener taskPerformer = new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        //...Perform a task...

        errorPromptLabel.setText("Checking your results! Please wait...");
        errorPromptLabel.setVisible(true);
    }
};

Timer timer = new Timer( 1000 , taskPerformer);
timer.setRepeats(false);
timer.start();

// This code is supposed to run AFTER the timer to show the results

CalculationResults f = new CalculationResults(String.valueOf(loanAmountInt), String.valueOf(loanInterestInt), String.valueOf(loanPeriodInt), String.valueOf(monthlyRepaymentInt), checkMonthlyRepayment, checkLoanPeriod);
this.setVisible(false);
f.setVisible(true);
this.dispose();

Upvotes: 0

Views: 131

Answers (1)

Chris K
Chris K

Reputation: 12341

What you want is to create a dialog box that is modal with your "calculating..." message, and then use your timer to cancel that dialog box and continue processing.

Timers are run asynchronously.

http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html

Although all Timers perform their waiting using a single, shared thread (created by the first Timer object that executes), the action event handlers for Timers execute on another thread -- the event-dispatching thread. This means that the action handlers for Timers can safely perform operations on Swing components. However, it also means that the handlers must execute quickly to keep the GUI responsive.

In your case you seem to have reversed the process. The ActionListener should do the work of disposing the "calculating..." message and setting the results, and you do your setup of the dialog before invoking the timer.

Thread.sleep() is the wrong thing to be using here.

Upvotes: 1

Related Questions