2013-01-11 62 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(即使它是相同的),你按下按鈕。