How to refer to the object that created the object?

In Java, I have an object that creates a button. Inside this onclicklistener button, I want to reference the object that created the button.

Is there any easy way to do this?

+3
source share
2 answers

It depends on how you structured it. In general, instances do not have a reference to the instance that created them, unless you pass it in and store it somewhere. However, if you do:

public class YourClass {
    public void foo() {
        JButton b = new JButton();
        b.addActionListener(new ActionListener() {
            @Override public void actionPerformed(ActionEvent e) {
                // Need reference to YourClass here
            }
        });
    }
}

then you can access the outside YourClassusingYourClass.this

+6
source

Sort of:

    class CustomButton extends Button
    {
         private Object parent = null;

         public CustomButton(Object parent) {
             super();
             this.parent = parent;
         }
    }

gotta do the trick.

+1
source

Source: https://habr.com/ru/post/1750948/


All Articles