I have a container which switches its main content between several screen-sized panes. I’m not using CardLayout, instead I’m using remove(previous); add(current); validate();
In this container I have data fields for each of these panes, which are initialized at startup so that I can easily just switch the reference between them.
My question:
If you remove the previous pane and add the new / current one, does the memory taken up by the previous pane’s instance object remain in memory?
Because I considered setting the previous pane to null and re-creating the current pane before adding it to the container in an attempt to lower memory usage, but wasn’t sure if it would actually make any difference.
Thanks. 🙂
EDIT: This isn’t actually my class but it demonstrates how I’m going about switching views:
public class ViewManager {
public static final int VIEW_LOGIN = 0;
public static final int VIEW_CALENDAR = 1;
public static final int VIEW_HELP = 2;
public static final int VIEW_SETTINGS = 3;
public static final int VIEW_PREFERENCES = 4;
public static final int VIEW_STATS = 5;
private static LoginPane login = new LoginPane();
private static CalendarView calendar = new CalendarView();
private static HelpPane help = new HelpPane();
private static SettingsPane accountSettings = new SettingsPane();
private static PreferencesPane preferences = new PreferencesPane();
private static StatsPane stats = new StatsPane();
private static int previousView;
private static Object [] views = {login, calendar, help, accountSettings, preferences, stats};
// Without settings old views to null and re-creating incoming view request
public static void switchTo(int currentView){
if(currentView == previousView) return;
MainFrame.getContent().remove(views[previousView]);
MainFrame.getContent().add(views[currentView]);
MainFrame.getContent().validate();
}
// Settings to null and re-creating incoming view request
public static void switchToNullify(int currentView){
if(currentView == previousView) return;
MainFrame.getContent().remove(views[previousView]);
views[previousView] = null;
if(currentView == VIEW_LOGIN) views[VIEW_LOGIN] = new LoginPane();
else if(currentView == VIEW_CALENDAR) views[VIEW_CALENDAR] = new CalendarView();
else if(currentView == VIEW_HELP) views[VIEW_HELP] = new HelpPane();
else if(currentView == VIEW_SETTINGS) views[VIEW_ACCOUNT_SETTINGS] = new SettingsPane();
else if(currentView == VIEW_PREFERENCES) views[VIEW_PREFERENCES] = new PreferencesPane();
else if(currentView == VIEW_STATS) views[VIEW_STATS] = new StatsPane();
MainFrame.getContent().add(views[currentView]);
MainFrame.getContent().validate();
}
}
Yes, unless you remove all references to that object. Once you’ve done that, it’ll be eligible for garbage collection.
Good idea!