开发者

swing question on resize controls on maximize

I have a JFrame with the following layout and components:

 _________________________________________ 
 |  __________________________________    | 
 |  |JTree   |   Panel2              | *  |
 |  |(Panel1)| (other controls)      |<-> |
 |  |________|_______________________|    |
 |__________*_____________________________|

These are in the contentpane of the main JFrame.

What I want is when I maximize the window, these components to resize accordingly.

What happens now is that they remain in their current size and there is a huge gap at the place I have the arrow and stars.(Side and bottom).

I would like to remain packed.

I have used null layout for content pane and dropped the components from a visual designer.

How can I make the controls alway开发者_运维百科s resize on mazimize?


If you want the two panels to have equal size, each occupying half of the main window, use GridLayout:

getContentPane().setLayout(new GridLayout(1,2));
getContentPane().add(Panel1);
getContentPane().add(Panel2);

If you want one panel to have constant width, use BorderLayout:

getContentPane().setLayout(new BorderLayout());
getContentPane().add(Panel1,BorderLayout.EAST);
getContentPane().add(Panel2,BorderLayout.CENTER);

If you want more complex behaviour, e.g. to maintain the 1:2 width ratio, you will have to use GridBagLayout which is the most powerful layout but also the most complicated:

getContentPane().setLayout(new GridBagLayout());
getContentPane().add(Panel1,new GridBagConstaints(0,0,1,1,1,1,GridBagConstraints.CENTER,GridBagLayout.BOTH,new Insets(0,0,0,0),0,0);
getContentPane().add(Panel2,new GridBagConstaints(1,0,1,1,2,1,GridBagConstraints.CENTER,GridBagLayout.BOTH,new Insets(0,0,0,0),0,0);


Don't use null layout, don't use a form designer, but rather experiment with the various layout managers. GridBagLayout may be one of the managers that could help you create a GUI as desired, but many try to avoid using this one unless necessary. Many also nest JPanels each with its own layout manager so in effect nesting the layout managers.


If you search SO you'll probably get many different opinions. There is one common truth though: you need to have at least a basic understanding of how a certain layout manager works before even thinking of using a visual designer.

Having said that, the best results I got, and what I currently use in production is a combination of the great WindowBuilderPro and MigLayout as a layout manager.

I actually use MigLayout as a table layout. I put my components in cells and I set each cell with attributes like "grow" - if I want to expand on resize, minimum/pref/max size, alignment, etc. I can set components to span across cells and I get exactly what I want.

The great thing about WindowBuilder is that you can change the generated code without messing the designer, and the generated code it's actually pretty :)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜