views:

393

answers:

4

Suppose I have this:

class external
{
    JFrame myFrame;
    ...

    class internal implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
             ...
             myFrame.setContentPane(this.createContentPane());
        }
    }
    ...
}

createContentPane returns a Container. Now, if I was doing this code outside of the ActionListener it would work, because I'd have access to this. But, inside it, I don't. I have access to myFrame, which is what is going to be updated with the contents of the method, but that isn't enough to do what I want, unless I can get a this out of it.

I also need information from other instance variables to use createContentPane(), so I'm not sure I can make it static.

+1  A: 

Not sure exactly what you're getting at, but an inner class has access to all of the members of its enclosing class. To access the "this" pointer of the enclosing class (e.g., to pass to other methods) use:

someMethod(External.this);

In your example, you're actually complicating it by using "this". Here are two options that will work:

myFrame.setContentPane(createContentPane());

or:

myFrame.setContentPane(External.this.createContentPane());

Note that you're already accessing myFrame in the same manner.

Dave Ray
argh, beat me by 8 seconds ;-) +1
David Zaslavsky
them's the breaks :) thanks.
Dave Ray
+1  A: 

external.this will give you access to the instance of the enclosing class, if that's what you want...

David Zaslavsky
+3  A: 

You can either :

myFrame.setContentPane(createContentPane());

or

myFrame.setContentPane(external.this.createContentPane());

By the way, in Java classes first letter is usually uppercase. Your code will still compile and run if you don't name it like that, but by following coding conventions you'll be able to read others code, and much more important other will be able to read your code.

So this would be a better style:

class External {
    JFrame myFrame;
    ...

        class Internal implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                ...
                myFrame.setContentPane(createContentPane());
               //Or myFrame.setContentPane(External.this.createContentPane());
            }
        }
    ...
 }

Java Code conventions

OscarRyz
A: 

First you have to extend JFrame in your outer class like this class External extends JFrame { ..... .....