1

In the following snippet:

public void main(){
    //Enclosing scope
    final TextField field = new TextField("", uiSkin) {
        @Override
        protected InputListener createInputListener() {
            return new TextFieldClickListener() {
                @Override
                public boolean keyUp(com.badlogic.gdx.scenes.scene2d.InputEvent event, int keycode) {



                    // error1 => The local variable field may not have been initialized
                    System.out.println("Field "+field+"event="+event+" key={}"+keycode);

                    // error2 => No enclosing instance of the type TextField is accessible in scope
                    System.out.println("Field "+TextField.this+"event="+event+" key={}"+keycode);



                    return super.keyUp(event, keycode);
                };
            };
        }
    };
}

Is there a way to refer the outer instance of the anonymous class from an inner anonymous class?

The second error is on the solution I found here Keyword for the outer class from an anonymous inner class . It seems that the problems share some concepts and problem space but are different in nature.

Community
  • 1
  • 1
raisercostin
  • 8,777
  • 5
  • 67
  • 76

1 Answers1

0

The problem can be fixed by defining a new field that captures the reference to the enclosing this.

//Enclosing scope
final TextField field = new TextField("", uiSkin) {
    TextField this2 = this;
    @Override
    protected InputListener createInputListener() {
        return new TextFieldClickListener() {
            @Override
            public boolean keyUp(com.badlogic.gdx.scenes.scene2d.InputEvent event, int keycode) {
                System.out.println("Field "+this2+"event="+event+" key={}"+keycode);
                return super.keyUp(event, keycode);
            };
        };
    }
};
raisercostin
  • 8,777
  • 5
  • 67
  • 76