Adam
Adam

Reputation: 33

How do I reference the object that created an object?

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

Is there some easy way I can do this?

Upvotes: 3

Views: 124

Answers (2)

Michael Mrozek
Michael Mrozek

Reputation: 175585

It depends how you structured it. In general, instances don't have a reference to the instance that created them unless you pass it in and store it somewhere. However, if you're doing:

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 refer to the outer YourClass, using YourClass.this

Upvotes: 6

cypher
cypher

Reputation: 6992

Something like:

    class CustomButton extends Button
    {
         private Object parent = null;

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

should do the trick.

Upvotes: 1

Related Questions