Lazy-initialization enabled CardLayout?
-
12-06-2021 - |
Question
I have a bunch of panels put in a CardLayout
where nth panel depends on the state changes caused in (n - 1)th panel. Since with CardLayout
, you have to initialize and add all panels beforehand. As such it makes it harder than necessary to manage state.
Does Java or some third party open source library provide a variation of CardLayout
that initializes its constituent panels lazily i.e. they are initialized just before they are going to be visible?
Edit:
Perhaps I did not state the problem clearly. Let me try again.
I need to set up the panels in CardLayout
beforehand, but I do not want it to initialize them until they are to be made visible. This is necessary so that the state changes from previous stages are transparently propagated to next stages.
In my current code, I have:
cardsPanel.add(ReadMePanel.create(this), ReadMePanel.ID);
cardsPanel.add(LicencePanel.create(this), LicencePanel.ID);
cardsPanel.add(InstallationPathPanel.create(this), InstallationPathPanel.ID);
cardsPanel.add(
ExtractionProgressPanel.create(
this,
new NormalizedPath(appContext.getParameter("zipFilePath")),
new NormalizedPath(appContext.getInstallationDirectory().toString())
),
ExtractionProgressPanel.ID
);
Here InstallationPathPanel
allows users to select a different installation directory than the default one. ExtractionProgressPanel
is supposed to extract a certain zip file to this directory. if ExtractionProgressPanel
were lazily initialized, the user selected path would be propagated to it, without me doing anything extra.
Hope the problem is clear now.
Solution
You can initialize and add the panel to the CardLayout
right before calling the show
method, so there is no problem.
EDIT
So on the location where you now call CardLayout#show
, you could first do an add
and then the show
As it looks like you are trying to create a wizard, the following article might be a good place to start