Fabricio
Fabricio

Reputation: 7935

How to pass a variable to a inner class

I want to use canvas inside mousePressed. How can I do that?

public DragManager(Canvas canvas)
{
    canvas.addMouseListener(new MouseAdapter() {
        @Override public void mousePressed(MouseEvent e)
        {
            canvas.something(); // does not work.
        }
    });
}

Upvotes: 1

Views: 1235

Answers (5)

Hosein Razaghi
Hosein Razaghi

Reputation: 144

without using final keyword. you can add Init method that return this and add private variable. pass canvas by Call Init method.

public DragManager(Canvas canvas)
{
    canvas.addMouseListener(new MouseAdapter() {
        Canvas _canvas;
        @Override public void mousePressed(MouseEvent e)
        {
            _canvas.something(); // does not work.
        }
        public MouseAdapter Init(Canvas canvas){
            _canvas = canvas;
            return this;
        }
    }.Init(canvas));
}

Upvotes: 0

om-nom-nom
om-nom-nom

Reputation: 62835

As many of the guys over here already said you have to make function parameter final.

public DragManager(final Canvas canvas)
{
    canvas.addMouseListener(new MouseAdapter() {
        @Override public void mousePressed(MouseEvent e)
        {
            canvas.something();
        }
    });
}

That means that this variable cannot point to any other object. E.g. you cannot do this inside function:

canvas = SomeOtherCanvas

If you create an object using a local class definition, that object can keep "living" after local variables have been discarded from the stack (after DragManager constructor completion). It has to have a copy of the local values. If you make this parameter final (so it's guaranteed that reference inside constructor wouldn't point to some other place) it's really easy to have a copy: just copy a reference. If there was no such rule you (well, not you personally, but Java language) would need to constantly sync those values and that would be much more complex and slow solution.

Upvotes: 3

PermGenError
PermGenError

Reputation: 46428

you Cannot refer to non final variable inside an inner class defined. mark your canvas as final.

public void DragManager(final Canvas canvas)
    {

        canvas.addMouseListener(new MouseAdapter() {
            @Override public void mousePressed(MouseEvent e)
            {
                System.out.println(canvas);;// does not work.
            }
        });

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691943

Make the parameter final:

public DragManager(final Canvas canvas)

Upvotes: 2

Korniltsev Anatoly
Korniltsev Anatoly

Reputation: 3686

public DragManager(final Canvas canvas)
{
    canvas.addMouseListener(new MouseAdapter() {
        @Override public void mousePressed(MouseEvent e)
        {
            canvas.something(); // does work.
        }
    });
}

since you can modify canvas variable, you should define it as final(constant reference).

Upvotes: 0

Related Questions