I have done a couple of simple swing based apps with static layout, but now I've run into a problem while trying to create an app containing multiple views which are changed by pressing appropriate navigational button.
You could compare the idea to a website so that every view has buttons to access certain other views but this would work inside a single JFrame.
I've found that maybe CardLayout 开发者_Go百科(Cardlayout example) might be appropriate solution for this kind of structure, but I'm unable to figure out a way to switch the views from the buttons which are inside of the JPanes that I've implemented in their separate classes,
Of course one way would be to instantiate everything in the parent class like in the small java tutorial example, but this isn't quite clean nor modular for multiple views, isn't it.
How can this be implemented so that I can access the view switching method?
Yes, CardLayout is specifically appropriated when having various views you want to switch in between. Obviously, like @medoal says, JTabbedPane could also be used. Anyway, considering you want to use a CardLayout with buttons inside panels allowing you to change visible panel, what you would do could be :
Create your panels and allow them to have an object implementing a given interface registered. This interface would contain a method covering the CardLayout#show(Container, String) method. Well, as an example, considering your panels all have their names set, and each of these names are different, you could write something like
public interface PanelToggler { public void toggleTo(String name); }
In the class containing the CardLayout, you would implementing the PanelToggler with something like
public void toggleTo(String name) { ((CardLayout) getLayout()).show(this, name); }
This way, in each panel, each button toggling viewed element from CardLayout would simply have to call toogleTo with the correct argument.
精彩评论