开发者

how to use the layout managers in swing java

开发者 https://www.devze.com 2023-03-01 06:01 出处:网络
I\'m new to layout managers like Flow, borders, ... I mostly use setBounds() to set the position of my components.

I'm new to layout managers like Flow, borders, ...

I mostly use setBounds() to set the position of my components.

I re开发者_如何学JAVAad on an article that using setBounds is not an good practice and it's better to use some layout.

Which are the best and most used layouts?

How to position a button using layout managers; instead of doing setbounds(10,10,100,30)?


look here: http://download.oracle.com/javase/tutorial/uiswing/layout/using.html

Basically you should forget about coordinates. Look at your dialogs at a higher level of design. Questions you should ask yourself.

1) Is there a "main" area with smaller surrounding areas in your design. If so use a BorderLayout.

2) Is there equal grid like areas in your design, If so use a GridLayout.

3) If you need a top-down, or left-right layout, consider a BoxLayout

4) If you want to show a complex form, probably use a FormLayout from jgoodies.

But you have to look at things from a high level. There may be subsections in any one top level section of your dialog. If that is the case, then you need to put a JPanel in that section, and then use a sub layout in that JPanel. Use the above questions over again for that panel.


Besides "standard" Swing layouts (part of the JDK), there are many third-party (mostly open source) LayoutManagers that often are much better than Swing ones.

For a comparison of many LayoutManagers on a real example (with code), check out this link, although a bit old, it still shows the various features and ease of use of predominant LayoutManagers nowadays.

In general, I would advise DesignGridLayout which, although quite powerful, is very easy to use (you don't need a GUI designer to use and it's easy to maintain layout code of existing panels); it just takes one hour to understand it.

Also, MigLayout is viewed as the most flexible one (might be useful if you need very complex layouts), but it takes more time to get used to it, and sometimes you have to use "tricks"to make it work as you want.


..which is the best and most used layout (?)

Nested layouts. Use whatever layout works best for different groups of GUI components, then put them in panels inside other panels (with other layouts). See this Nested Layout Example for a demo. of combining layouts.

As to which best individual layouts to use, do the tutorial linked by MBFG to get a feel for what each can achieve, their strengths & weaknesses.

I will commonly use nested combinations of BorderLayout, GridLayout & FlowLayout, with an occasional GridBagLayout.

0

精彩评论

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