1

I am trying to do following in gui class for notifying registred observers.

public class GUI extends javax.swing.JFrame implements Observer {

public notImportantMethod() {

 t = new Thread() {
            @Override
            public void run() {
                for (int i = 1; i <= 10; i++) {
                       myObject.registerObserver(this);   
                 }
            }

        };
        t.start();
      }
}

It gives me error: incompatible types: cannot be converted to Observer How can I use this? I know inside of run there is another context but how could I access it?

dtechlearn
  • 363
  • 2
  • 4
  • 21
  • What actual object are you trying to register? The thread or the instance of GUI? – Steve Smith Apr 06 '17 at 14:37
  • I am trying to register gui – dtechlearn Apr 06 '17 at 14:39
  • 1
    `OuterEnclosingClassname.this` i.e. `GUI.this` will give you reference to the current object of the outer enclosing class, GUI . When you use simply `this` it refers to the object of anonymous class extending `Thread` – nits.kk Apr 06 '17 at 14:49
  • Note: your question really is not about threads. Your question is about how a method of an _anonymous inner class_ can refer to the instance of the enclosing class for which the inner class instance was created. The fact that your inner class extends `Thread` doesn't change the answer. – Solomon Slow Apr 06 '17 at 15:18

3 Answers3

3

this now refers a Thread. You should be able to call GUI.this. For more info, see here .

Community
  • 1
  • 1
Ishnark
  • 661
  • 6
  • 14
0

If you're looking for quick and dirty: (this is not good practice)

public notImportantMethod() {

final GUI self = this;

 t = new Thread() {
            @Override
            public void run() {
                for (int i = 1; i <= 10; i++) {
                       myObject.registerObserver(self);   
                 }
            }

        };
        t.start();
      }
}

Otherwise I would recommend looking up a tutorial on multi-threading and/or concurrency in java, like this one: http://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/

otoomey
  • 939
  • 1
  • 14
  • 31
-1

@Ishnark has answered it correctly. You should be able to access it via GUI.this, that's all that you need to do.

Suraj Kumar
  • 109
  • 1
  • 3
  • 15