Home > Enterprise >  How to utilize sleep method for calculator error
How to utilize sleep method for calculator error

Time:07-02

I am trying to set the calculator text to an error message, wait for 2 seconds, then clear the field text. Below is my current code.

public static void wait(int ms) {
    try {
        Thread.sleep(ms);
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
}

// TODO: 6/30/22 if decimal is clicked multiple times -> setText("Error")
    if (field.getText().contains(".") && e.getSource() == decButton) {
        field.setText("error text here");
        wait(1000);
        field.setText("blank here");
    } else if  (e.getSource().equals(decButton)) {
        field.setText(field.getText().concat("."));
    }

So far, the field text sets directly to ("blank here") and completely skips the error message. I have tried moving the error message to different areas of the program (within the if statement) but have yet to find a conclusion.

CodePudding user response:

Are you using Swing? Is the code you show running from an event handler (triggered by keypress, mouseclick or something)? Then this cannot work.

The code is running in the Event Dispatcher Thread (EDT). Once you use something like field.setText() you have to exit your code and allow the EDT to fire the updates into the UI. But instead, you 'keep it busy' by waiting a second, then requesting the next update into the UI. Only then your method exits, and the user did not see the first message.

What you need to do is to set the update, then free up the EDT. How do you get the message to disappear one second later? Use a Swing Timer to trigger the action:

field.setText("error text here");
ActionListener errorHider = new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        field.setText("blank here");
    }
};
Timer t = new Timer(1000, errorHider);
t.setRepeats(false);
t.start();
  • Related