1

I'm not sure if this deserve a question but here it is.

If I have some Class, let's say

public class myClass{
   Button btn = new Button;
   btn.setOnMouseEvent(myHandler);
   Text txt = "hello";
}

Now if the user triggers the event I'll execute some code in myHandler. In there i need to access the txt variable but I only have a reference to the button via event.getSource().
So how can I obtain a reference to the class containing the object beeing returned by event.getSource()?

Edit : Ideas about the title are also welcome!

0

2 Answers 2

1

The answer is actually pretty simple:

when an event handler instance X depends on some Y object, then Y needs to be made available to X.

For example by:

  • adding a Y field to the class of X
  • and by then passing a Y instance when doing new X(someY); for example

In other words: when your MyClass (class names should go UpperCase!) instantiates the myHandler object, it could pass "itself" (via this to the handler). Of course, that can lead to circular dependencies (bad), one way out of that:

  • Y implements SomeInterface
  • the handler only gets to know SomeInterface, and it never knows or cares that the SomeInterface instance passed to it ... happens to be of type Y.
Sign up to request clarification or add additional context in comments.

Comments

0
If you are the one who crated MyHandler and if you can still modify the class then below style can be helpfull:


public class myClass{
   Button btn = new Button;
   Text txt = "hello";
   MyHandler myHandler = new MyHandler();

   myHandler.setMsg(txt );
   btn.setOnMouseEvent(myHandler);

}
class MyHandler {
    private msg;
    public setMsg(String msg){
      this.msg = msg;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.