Kristjan Toots
Kristjan Toots

Reputation: 81

Is it possible to add components dynamically to the middle of BoxLayout

I'm building a small swing application where I've created contentpane with BoxLayout aligned to Y axis and added another 2 JPanels to it. So far so good.

Now I've stumbled upon a problem where I have to re-create the first JPanel and add it to the middle of other two JPanels.

There might be more than one occurrence where another panel is added to the layout so I wish it would expand appropriately.

Conclusion: What I'm looking for is to add components to the BoxLayout with option to add them before the last component.

Thanks.

Upvotes: 2

Views: 688

Answers (2)

camickr
camickr

Reputation: 324118

Check out the Container API. The add(...) method has overloaded methods that allow you to specify the position of the component in the container. Then revalidate() and repaint() the panel.

Upvotes: 5

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

I would simply remove all components and then re-add them in the order desired being sure to call revalidate() and repaint() on the BoxLayout-using container after you've completed this action.

If you need your GUI itself to change size, then you may have to call pack() on the top-level window that holds these components.

Upvotes: 4

Related Questions