Layout Managers


You can position components on a container by using absolute positioning, but this technique is painful and usually unnecessary. The better way to go is using a layout manager that handles positioning for you, based on simple rules. An excellent feature in Swing is having a default layout manager for every container. You can always replace the default with another one, but you don't have to. Every container, by default, has a layout manager. For example, BorderLayout is the default layout manager for every content pane. There are many more layout managers than just these, including DefaultMenuLayout, OverlayLayout, ScrollPaneLayout, SpringLayout, TextLayout, and ViewportLayout, but the following six layout managers are the ones I recommend you use for your solution.

  • FlowLayout ” Components are arranged in a left-to-right flow. This is the default.

  • GridLayout ” Components are arranged in a grid or table.

  • BorderLayout ” Components are arranged in five areas: north, south, east, west, and center.

  • CardLayout ” Panels overlap as in a tabbed pane, but without the tabs.

  • BoxLayout ” This fancier version of the FlowLayout stacks its components on top of each other or left to right.

  • GridBagLayout ” This layout manager is the most flexible. It is like the GridLayout, except the cells can vary in size instead of having all rows or columns the same size.

The following code shows how you could lay out components left to right, in two rows and two columns:

 JButton firstComponent = new JButton; JButton secondComponent = new JButton; JButton thirdComponent = new JButton; JButton fourthComponent = new JButton; int rows = 2; int columns = 2; JPanel panel = new JPanel(new GridLayout(rows, columns)); panel.add(firstComponent); panel.add(secondComponent); panel.add(thirdComponent); panel.add(fourthComponent); 


JavaT 2 Developer Exam CramT 2 (Exam CX-310-252A and CX-310-027)
JavaT 2 Developer Exam CramT 2 (Exam CX-310-252A and CX-310-027)
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 187

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net