Search code examples
javaswingdelayjtextarea

How to add delay inside a JTextArea in displaying text?


I want to add delay in displaying text in a textArea. I use Thread.sleep method but it is not working properly.

for(int i=0; i<3; i++) {
    textArea.append(" .");
    Thread.sleep(2000);
}

This part of code is inside the actionListner of a button. When button is pressed a single dot(.) is displayed inside the textArea each by 2 sec delay but the loop is not working correctly. When I run the code the program first wait for 6 seconds then the whole output is shown at once in the textArea.

However if I use this part of code in a simple java class other than GUI then it work totally fine.

Please help me how can I do this?


Solution

  • You can use a Timer, all you have to do is:

    1) import

    import javax.swing.Timer;
    

    2) initialise with his own Action Listener

    private int i = 0;
    private Timer tmr = new Timer(2000, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            textArea.append(" .");
            ++i;
            if(i >= 2)
               tmr.stop();
        }
    });
    

    3) start your timer with:

    tmr.start();
    

    This should work. Let me know if there is any issue.