Java Swing: Change Text after delay

安稳与你 提交于 2019-11-28 01:31:28
MadProgrammer

Swing is an event driven environment. While you block the Event Dispatching Thread, no new events can be processed.

You should never block the EDT with any time consuming process (such as I/O, loops or Thread#sleep for example).

You might like to have a read through The Event Dispatch Thread for more information.

Instead, you should use a javax.swing.Timer. It will trigger a ActionListener after a given delay.

The benefit of which is that the actionPerformed method is executed with the context of the Event Dispatching Thread.

Check out this or this or this or this for an examples

it works after 3 seconds..

ActionListener taskPerformer = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            statusbar.setText("Status");
        }
    };
    Timer timer = new Timer(3000, taskPerformer);
    timer.setRepeats(false);
    timer.start();

if these piece of code is in the event handlers, then you are holding up the UI thread, and it is not going to work as UI update will only happens after you finished your work in the event handlers.

You should create another thread do the work of "sleep 3 second, and change the text field, and trigger repaint". Using Timer or similar utilities is the easiest way to achieve what I am describing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!