开发者

Best layout strategy if removing/adding components in a Java Swing UI?

I have a dynamic java Swing form UI that needs to resize when a toggle button is pressed. Components inside the form panel need to be removed or added and the height accordingly reduced/increased.

Cardlayout allows me to switch between two panels with different components but the height is hardwired to the the tallest card. I need to dynamically remove swing components and reduce the height of the inner panels as well as the entire main panel.

Using Grouplayout with setHonorsVisibility(true) doesn't work either unless the entire layout hierarchy is re-created. There is no way to get rid of the gaps between components being hidden.

BoxLayout may sort of works but with a box container it will be a pain to lay开发者_如何学运维out the form elements to align nicely. So I haven't tried it.

I would like to work with Netbeans GUI builder if possible but the default GroupLayout doesn't work for me. So looking at other design patterns/strategies to solve this.

I would hate to manually setPreffered dimensions on nested panels.

How to people deal with re-packing the UI after removing components ?


You're probably going to have to go with a multi-pronged attack, like you've already laid out.

1) cardlayout for swapping - helps to keep unrelated things seperate

2) whatever kind of layout you need for each card.

Originally i did a lot of nested BorderLayout panels, then moved on to GridBagLayout for almost everything. While complicated to learn, it is the most flexible. It probably isn't very guibuilder friendly, though.

Worst case, you could write your own layout...but that's complicated with lots of gotchas...

With swapping/visibility you may require a bunch of validate/invalidate/repaint, or forced calls to doLayout as well.


The way I have done it in the past is by using GrdBagLayout. This allows you to specify where objects will live, whether they will fill or not in their cell, and it sets the size of the cell to the minimum size to let the components play nice with each other. Follow this with a frame.pack(), and you will have auto-resizing dialogs. Note, that you have to set the dimensions (iirc, it is minimum and not preferred, although I could be wrong) along with the grid bag constraints (weight, cell, which part of the cell it binds to, etc).

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜