2013-01-11 63 views
1

我正在为我的课写一篇基于文本的小游戏。导航很简单,玩家点击按钮输入不同的部分。所有这些部分都被分成它们自己的代码块。到目前为止,我只设置了两个部分,每个部分都可以通过按钮与另一个部分相连。基本上是:缓慢运行,高内存使用率

private void level1() { 
//Stuff here, player clicks a button which runs "level2();" 
} 

private void level2() { 
//Stuff here, player clicks a button which runs "level1();" 
} 

所以这工作得很好,但有些点击来回1 & 2之间后,该程序开始运行非常缓慢。任务管理器报告大约700MB的内存使用量。

我确定有一些事情真的很明显,我错过了。我正在寻找一种让用户能够多次点击多个按钮的方式,而不是让程序使用这么多资源。非常感谢帮助。

编辑:一些更多的代码。 Choice1-3是按钮的名称。变量已经在程序的顶部声明,并在初始化部分中设置。他们与和每个代码块,如场景1 2

private void setScene1() // TITLE SCREEN 
{ 
    TITLE.setText("Title Label"); 
    main.setText("Main text body for the game."); 
    choice1.setText("Play"); 
    choice1.setBounds(10, 600, 996, 91); // This makes choice1 as large as 
              // all three buttons combined. 
    choice2.setEnabled(false);// There's only one option anyway. 
    choice3.setEnabled(false); 
    choice2.setVisible(false); 
    choice3.setVisible(false); 

    choice1.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent arg0) { 
      setScene2(); 
     } 
    }); 

} 

private void setScene2() // CHARACTER GENERATION SCENE 
{ 
    TITLE.setText("Character Generation"); 
    main.setEnabled(false); // Disable & Hide the main text window, as 
          // Chargen requires a nicer looking interface. 
    main.setVisible(false); 
    choice2.setEnabled(true); 
    choice2.setVisible(true); 
    choice1.setBounds(10, 600, 996, 34); //Resizing the bottom portion to fit two buttons 
    choice2.setBounds(10, 645, 996, 34); 
    choice1.setText("Continue"); 
    choice1.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent arg0) { 
      // Nothing here for now 
     } 
    }); 
    choice2.setText("Back to the Title Screen"); 
    choice2.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent arg0) { 
      main.setEnabled(true); 
      main.setVisible(true); 
      setScene1(); 
     } 
    }); 

} 
+3

代码在哪里?没有它,SO不能真正帮助 – fge

+2

你能向我们展示level1()和level2()的onClick事件吗?我的第一个猜测是你正在创建新的对象,而不是重复使用已经存在的对象。如果你点击的次数足够多,你最终会得到许多'level1'和'level2'对象,但一次只能有一个活动/可见。 – Grambot

+0

对,对不起。我现在只是增加了一些。我的确在重新使用对象。 – Railrunner

回答

2

问题似乎在于您每次切换场景时都要添加一个ActionListener。以前的ActionListener永远不会消失,但是你可以在它上面堆叠更多的东西来做同样的事情。每个人执行相同的动作,所以当你按下切换场景时,它现在拥有的所有ActionListners也将切换场景。你的CPU会上升,因为现在有2^n个ActionListeners在等待输入,并且有很多坐在内存中。

+0

那么从这个和以前的回答中,我刚刚在后台运行了大量不同的进程,它们都没有做任何事情?我能做些什么来终止这些方法吗? – Railrunner

+0

您可以使用该组件的getActionListeners()方法,然后遍历并在每个方法上执行removeActionListener()。有一个例子描述如何做到这一点http://stackoverflow.com/questions/4048006/java-swing-how-to-remove-an-anonymous-actionlistener-from-a-component – nhydock

+0

更多的建议修复方法你的问题是当你实例化它们所连接的对象时,只添加ActionListeners,而不是每次设置你的场景。你的场景实际上应该是两种不同的JLayers,它们有自己的组件,可以翻出来,而不是每次重写所有组件的属性。 – nhydock

2

进行修改。如果上述两种方法继续通过你的内存来称呼对方你最终会吃:这是递归。如果你永远不会回电话树,它会变得任意深,直到繁荣。

1

您应该在构造函数或其他地方添加ActionListeners。这样你每次添加一个新的ActionListener(即使它是相同的),你按下按钮。