I’m writing a small text-based game for my class. The navigation is simple, in which the player clicks buttons to enter a different part. All of these parts are separated into their own blocks of code. I’ve set up only two parts so far, each of them being able to reach one another through buttons. Basically:
private void level1() {
//Stuff here, player clicks a button which runs "level2();"
}
private void level2() {
//Stuff here, player clicks a button which runs "level1();"
}
So that works just fine, but after some clicking back and forth between 1 & 2, the program starts to run very slow. Task Manager reports about 700MB of memory usage.
I’m sure there’s something real obvious that I’m missing. I’m looking for a way for the user to be able to click many buttons, many times, and not make the program use so much resources. Help would be very much appreciated.
Edit: Some more code. Choice1-3 are the names for the buttons. Variables are already declared at the top of the program, and set up in the initialize part. They’re to be modified with each block of code, such as Scene1 and 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();
}
});
}
The problem seems to lie in the fact that you’re adding an ActionListener every time you switch scenes. The previous ActionListener is never going away, but you’re stacking more on top of it that do the same thing. Each one performs the same action, so when you press to switch scene, all the ActionListners that it now has will also go to switch scene. Your CPU will go up because there’s now 2^n ActionListeners waiting for input and there’s that many sitting in memory.