tags:

views:

68

answers:

2

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?

+1  A: 

Something like:

    class CustomButton extends Button
    {
         private Object parent = null;

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

should do the trick.

cypher
+6  A: 

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

Michael Mrozek