简体   繁体   English

在CardLayout中更换卡片时如何创建新对象?

[英]How do I create new object while changing cards in CardLayout?

Currently I'm using CardLayout to jump between different guis in my game (main menu, settings, scoreboard etc.): 目前我正在使用CardLayout在游戏中的不同guis之间跳转(主菜单,设置,记分牌等):

    static JPanel panels = new JPanel();
    static CardLayout cl = new CardLayout();
    panels.setLayout(cl);
    panels.add(new Menu(), "menu");
    panels.add(new Game(), "game");
    panels.add(new Scoreboard(), "scoreboard");
    panels.add(new Settings(), "settings");
    panels.add(new Info(), "info");

and then in the same class I got static method that allows me to jump between game's JComponents (Menu, Game, Scoreboard, Settings, Info). 然后在同一个班级我得到了静态方法,允许我在游戏的JComponents(菜单,游戏,记分牌,设置,信息)之间跳转。

public static void changePanel(String panel){
    cl.show(panels, panel);
}

Unfortunately all of those objects are created at the start of the game. 不幸的是,所有这些对象都是在游戏开始时创建的。 I need to create new object each time when card is changed and delete old object to save memory. 我需要在每次更换卡时创建新对象并删除旧对象以节省内存。 Is that passable? 这可以通过吗?

Your best option is to call System.gc() which simply is a hint to the garbage collector that you want it to do a collection. 您最好的选择是调用System.gc(),这只是对垃圾收集器的一个提示,您希望它能够进行收集。 There is no way to force an immediate collection though as the garbage collector is non-deterministic. 由于垃圾收集器不确定,因此无法强制立即收集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM