Kryonet listener to Slick2d

When KryoNet recieves the LoginAnswer package, i want to set the field of NFTClient String name (Line 4) to the ((LoginAnswer)object).name variable (Line 21) in order to use it in the Render method. How can i do that?


public class NFTClient extends BasicGame {

    Client client;
    String name;

    public NFTClient() {
        super("Client");
        client = new Client();
        client.start();

        Network.register(client);

        // ThreadedListener runs the listener methods on a different thread.
        client.addListener(new Listener.ThreadedListener(new Listener() {
            public void connected(Connection connection) {
            }

            public void received(Connection connection, Object object) {

                if (object instanceof LoginAnswer) {
                    String name = ((LoginAnswer) object).name;
                }

            }

            public void disconnected(Connection connection) {
                System.exit(0);
            }
        }));

        try {
            client.connect(5000, "localhost", Network.port);
            // Server communication after connection can go here, or in Listener#connected().
            System.out.println("heJ");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void init(GameContainer gc) throws SlickException {
    }

    public void render(GameContainer gc, Graphics g) throws SlickException {
        g.drawString(this.name);
    }

    @Override
    public void update(GameContainer gc, int delta) throws SlickException {
    }

    public static void main(String[] args) throws SlickException {

        Log.set(Log.LEVEL_DEBUG);
        AppGameContainer app = new AppGameContainer(new NFTClient());

        app.setDisplayMode(768, 512, false);
        app.setTargetFrameRate(60);
        app.start();

    }
}


This is just bugging me, i can’t seem to find anything on the subject anywhere.

I really hope someone here can help out! :slight_smile:

Im not exactly sure what you want, but it would seem that line 21 should be simply

this.name = ((LoginAnswer) object).name;

That is exactly what i want, however that is not working. It seems that the codeblock in the Listener behaves like its own class.
Netbeans suggests adding the field name in the Listener. (Line 15 that is)
I sure hope there’s a way to “break out” of this block

ah yeah one of the annoying things about listeners
I use some workarounds which aren’t - I’m sure someone else here knows how to do this properly

Yes. There is a way to “break out”. You have an inner class there. The listener is indeed a new class.

To get access to the object of the class you defined the inner class (the listener) in, simply use [icode]SuperClass.this.field[/icode], so in this case [icode]NFTClient.this.name = ((LoginAnswer) object).name;[/icode].

I guess this should work :slight_smile: