Swing: "thin" standard component to act as a container?
I need to pick a standard container (JPanel?) in Swing that I can use as a placeholder to which I can add another custom component that extends JPanel:
JPanel containerPanel;
// built by a library from a text file, automatically part of a nice layout
MyPanel componentPanel;
// something complicated that I can't integrate with the builder library
containerPanel = builder.getMyContainerPanel();
componentPanel = new MyPanel(...);
containerPanel.add(componentPanel);
Is there a way开发者_JS百科 to somehow couple the two panel sizes so that resizing works properly? I'm not quite sure how resizing works in swing, but what I want is for the outer containerPanel
to be a thin wrapper that is subservient to my componentPanel
and the outer panel delegates as much as possible to the inner panel.
I don't want to do things this way but it seems like the best way to decouple the builder library from my custom component.
I'd simply use a GridLayout
.
containerPanel.setLayout(new GridLayout(1, 1));
This has the advantage that you can just add the sub panel without any parameters and it is guaranteed to use the entire area:
containerPanel.add(componentPanel);
You can use a BorderLayout
and add your delegate container in the BorderLayout.CENTER
position.
Hmm. Well, I decided to rewrite my component, so instead of a class that extends JPanel (inheritance), it uses composition and is constructed with an empty JPanel as a parameter + it adds child components to the JPanel. So I can use the builder library to build the empty JPanel, then later I pass that into my own component's constructor, so now I have 1 JPanel instead of two of them that I have to keep coupled together.
精彩评论