Reputation: 825
I have a main JFrame which holds a default JPanel. I'm trying to use this JPanel to attach different JPanels to my application to simulate the effect of browsing through the application. I noticed that for CardLayout to work, the JFrame usually has to have some way of controlling what is displayed in the JPanel (ex. a button, drop down box, etc.) What I'm attempting to do is have a home page(JPanel) load up into the default JPanel in the JFrame and allow the user to navigate using the clickable buttons/icons available in that home JPanel.
Since the JFrame and default JPanel are in a separate class from the rest of the JPanels, I'm having trouble accessing the default JPanel (since it is private) to change what appears on it by clicking a button on a JPanel in one of the other classes. Is there any way around this?
Also, would it work if I attached every button necessary in the application to the JFrame and controlled the JPanel displayed from there? I could make the button visible/invisible as necessary, does this make sense?
This is the code I'm calling in the JFrame class:
private void jButton45MouseClicked(java.awt.event.MouseEvent evt) {
CardLayout card= (CardLayout) displayPanel.getLayout();
card.show(displayPanel, "register");
}
displayPanel is the default Panel that cycles through all the cards and jButton45 is a button titled "Register" in the JFrame. "register" is the name of the JPanel variable which I'm trying to display.
Upvotes: 0
Views: 1095
Reputation: 83527
This sounds like a design issue. Without seeing some code, I cannot give specific details. That being said, the main thing you need to address is providing the buttons that control navigation with a reference to the default JPanel and its CardLayout. From there it is simply a matter of calling next()
, previous()
, or show()
.
Addendum:
The second argument to show()
is is the name that you provide when you call add()
. If you are using the NetBeans GUI Builder, you can set this in the properties window. Select the panel and scroll down to "Layout". Set the Card Name to the desired String value and then use this same value when you call show()
.
Upvotes: 2
Reputation: 347184
Use a model that can talk between you navigation pane (home) and the "default" used to switch the CardLayout
view.
Basically, the model would have simple setters and getters that can be used by the two parts of the application to change and observer the state of the model. You would need to provide some kind of listener to notify interested parties that the model has changed, the most simplest might be ChangeListener
or PropertyChangeListener
.
This way you can change the model over time without effect those components using it.
Upvotes: 1