开发者

Java- not removing from HashMap

OK so I have this HashMap

private Map<String, Player> players = new HashMap<String, Player>();

Here is what I use to remove:

      public void destroy() {

players.remove("Red");
os.println(me.getUsername() + "|1|has left|yes|chat");

      }

I say Red because it's just a TEST right now. I will get the eventual correct one later. Anyways...

I use THIS to check.

  if (e.getKeyCode() == KeyEvent.VK_Q) {
            for (Player playert : players.values()) {
                                        c.append("\n < "+playert.getUsername() + " > ");
                        }
                    }

When I'm all by myself.. I press Q and I get:

< Dan >

then my friend Red logs in and I Press Q... I get:

< Dan >
< Red >

then he leaves I press Q and I get:

< Dan >
< Red >

So.. how come this isn't working?

Also, here is the code that gets called in init() when a player logs in the game (starts the applet)

 public void playerLogin() throws IOException {

            Random roll = new Random();
            int newNo = roll.nextInt(200);
            // me.getUsername() = "Guest #" + roll.nextInt(110);
            // String me.getUsername() = getParameter("name");

            me = new Player();
            me.setUsername(getParameter("name"));
            me.setPlaye开发者_如何学编程rImage(ImageIO.read(getClass().getResource("me.gif")));
            me.setX(256);
            me.setY(256);
            me.setMap(1);
            me.setCommand("move");
            players.put(me.getUsername(), me);

            repaint();

            System.out.println(me.getUsername() + " was added. player: " + me);
            os.println(me.getUsername() + "|" + me.getX() + "|" + me.getY() + "|"
                        + me.getMap() + "|" + me.getCommand());

            attack = 4;
            defense = 5;
            gold = 542;
            level = 1;
            exp = 53;

      }


In other words, your Applet#destroy() method is not called at the moment you expect it is called? You should use Applet#stop(). The destroy() is only called when the object in question is eligible for GC and/or when the whole browser instance is been closed (and thus not only the current page/tab). JVM may namely keep running as long as the browser instance runs.


When you hit Q... you are checking the contents of players but where is your call to destroy()? Do you explicitly call destroy() anywhere in your code?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜