开发者

How to - Java Thread Accessing Other Thread (SWING)

开发者 https://www.devze.com 2023-04-04 10:52 出处:网络
Regarding the problem, when i start a thread from the main application, le开发者_Python百科ts say process A runs in background and updates a text box outside of the thread saying it\'s running and c

Regarding the problem,

when i start a thread from the main application, le开发者_Python百科ts say process A runs in background and updates a text box outside of the thread saying it's running and completed when it has stop running.

How do i write the code which updates the textbox outside the thread from within the running thread ?


you need a pointer to the text box. the thread cannot update the text box - in swing, all GUI commands must be executed from the event dispatch thread.

you must do:

SwingUtilities.invokeLater ( new Runnable(){
    public void run(){
        // draw textbox code
    }
});

this will add the object to the queue executed by the event dispatch thread

EDIT: just a tip: inside the new Runnable(){ ... }, which is an anonymous class, you won't be able to use a regular variable from the outside scope. You must define a variable as final, or use a getter to fetch the textbox (or address it through some static field).

0

精彩评论

暂无评论...
验证码 换一张
取 消