开发者

Update UI from parent class on different thread from secondary class

开发者 https://www.devze.com 2023-01-11 18:55 出处:网络
I have a parent class which builds my UI (basically just a text box at the moment).I have created a secondary class which c开发者_StackOverflow中文版reates a new thread and I need to be able to update

I have a parent class which builds my UI (basically just a text box at the moment). I have created a secondary class which c开发者_StackOverflow中文版reates a new thread and I need to be able to update the textbox on the parent class from the new thread. Everything I try throws errors. I'm assuming I need to create some kind of dispatcher but my background is C# and I'm not 100% familiar on how to do this in Java.

My latest iteration passes the object of the parent class to a static method in the secondary which ultimately creates the new thread by instantiating an object for the secondary class (which has the run() method inside). I have a constructor in the secondary object that expects the passed in object from the parent class which, when passed in, sets a property that I've decalred in my member section for the parent class. when I try to access that member in the run() method to update a textbox on the parent class, I get an error.

Essentially the secondary class looks something like this:

        public class SecondaryClass extends Thread {
    private ParentClass pc = null;
    public SecondaryClass(ParentClass PC){
    pc = PC;
    }
    public static void StartThread(ParentClass pC){
       Thread thread = new SecondaryClass(pC);
       thread.start();
    }
    public void run() {
      pc.myTextBox.append("something");
    }
}

I've also tried creating a public method on the parent class that accepts a string as it's only argument and calling that method from within run() on the secondary class and passing "somethign" there. The method on the parent class updates the same textbox but having problems there as well.

can anyone please provide some insight as to what I need to do to access UI elements across these threads?


you will need to use SwingWorker

Similar question answered on stackoverflow for J2ME:

Interacting with UI threads in Java/J2ME

Also read following:

http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html

http://java.sun.com/products/jfc/tsc/articles/threads/threads2.html

Check simple example here:

http://download.oracle.com/javase/tutorial/uiswing/concurrency/worker.html

Hope this helps.

0

精彩评论

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