我为下一个bug苦苦挣扎了好几个小时。我的程序结构如下
main
函数初始化一个Game
对象并调用startMainWindow()
,后者初始化一个GameLogic logic
对象和一个MainWindow
对象(将logic
作为参数传递给它,还将this
作为参数传递给它)。这两个对象都是 startMainWindow()
中的局部变量。
问题是,假设玩家玩完游戏后,我想启动高分图形用户界面,我从MainWindow
调用_game.startHighScoreWindow()
。问题是GameLogic
对象一直在运行!通过在GameLogic.actionPerformed()
中输入控制台写命令,我可以轻松地检查它。它不会从内存中释放。即使我在_game.startHighScoreWindow()
之前调用this.dispose();
,也会发生这种情况。
为什么_gameLogic
还在内存中?
下面是一些代码:
PacmanGame:
public void startMainWindow(int levelIndex, int levelsDone, int score) {
gameGui = null; //desperate attempt
highScoreGui = null;
mainMenuGui = null;
spaceGui = null;
gameLogic = null;
System.gc();
gameLogic = new GameLogic(_sprites, _levels[levelIndex], levelsDone, score);
gameGui = new MainWindowGui(this, gameLogic, _sprites, _levels);
}
public void startHighscoreGui(int score, String time) {
gameGui = null;
highScoreGui = null;
mainMenuGui = null;
spaceGui = null;
gameLogic = null;
System.gc();
highScoreGui = new HighscoreGui(this, score, time);
}
MainWindow:
public class MainWindow extends JFrame implements KeyListener {
private PacmanGame _game;
private GameLogic _gameLogic;
private GamePanel _gamePanel; //JPanel
private ToolbarPanel _toolbarPanel; //JPanel
private Sprite[] _sprites;
private Level[] _levels;
public MainWindow(PacmanGame game, GameLogic gameLogic, Sprite[] sprites, Level[] levels) {
// create our window
super("Pacman");
// initialize fields
_game = game;
_sprites = sprites;
_gameLogic = gameLogic;
_levels = levels;
this._gamePanel = new GamePanel(_gameLogic, _sprites);
this._toolbarPanel = new ToolbarPanel(_gameLogic, sprites, this);
...
}
public void playerWon(String time) {
Level levelObj = _gameLogic.getLevelObject();
int nextLevelIndex = (levelObj.getNum()) % 3;
if(_gameLogic.getLevel() == 3) //done!
{
this.dispose();
_game.startHighscoreGui(_gameLogic.getScore(), time);
}
else //next level
{
_gameLogic.nextLevel(_levels[nextLevelIndex]);
}
}
编辑:在一次孤注一掷的尝试中,我尝试在PacmanGame中创建所有的GUI和GameLogic静态变量,然后每次在PacmanGame中调用函数时将它们设置为null。它保持与以前一样的行为,也就是说,所有这些对象都是每个函数的本地对象。
https://stackoverflow.com/questions/50689605
复制相似问题