001package horstmann.ch05_layout; 002import java.awt.Component; 003import java.awt.Container; 004import java.awt.Dimension; 005import java.awt.Insets; 006import java.awt.LayoutManager; 007 008/** 009 A layout manager that lays out components along a central axis 010 */ 011public class FormLayout implements LayoutManager 012{ 013 public Dimension preferredLayoutSize(Container parent) 014 { 015 Component[] components = parent.getComponents(); 016 left = 0; 017 right = 0; 018 height = 0; 019 for (int i = 0; i < components.length; i += 2) 020 { 021 Component cleft = components[i]; 022 Component cright = components[i + 1]; 023 024 Dimension dleft = cleft.getPreferredSize(); 025 Dimension dright = cright.getPreferredSize(); 026 left = Math.max(left, dleft.width); 027 right = Math.max(right, dright.width); 028 height = height + Math.max(dleft.height, 029 dright.height); 030 } 031 return new Dimension(left + GAP + right, height); 032 } 033 034 public Dimension minimumLayoutSize(Container parent) 035 { 036 return preferredLayoutSize(parent); 037 } 038 039 public void layoutContainer(Container parent) 040 { 041 preferredLayoutSize(parent); // Sets left, right 042 043 Component[] components = parent.getComponents(); 044 045 Insets insets = parent.getInsets(); 046 int xcenter = insets.left + left; 047 int y = insets.top; 048 049 for (int i = 0; i < components.length; i += 2) 050 { 051 Component cleft = components[i]; 052 Component cright = components[i + 1]; 053 054 Dimension dleft = cleft.getPreferredSize(); 055 Dimension dright = cright.getPreferredSize(); 056 057 int height = Math.max(dleft.height, dright.height); 058 059 cleft.setBounds(xcenter - dleft.width, y + (height 060 - dleft.height) / 2, dleft.width, dleft.height); 061 062 cright.setBounds(xcenter + GAP, y + (height 063 - dright.height) / 2, dright.width, dright.height); 064 y += height; 065 } 066 } 067 068 public void addLayoutComponent(String name, Component comp) 069 {} 070 071 public void removeLayoutComponent(Component comp) 072 {} 073 074 private int left; 075 private int right; 076 private int height; 077 private static final int GAP = 6; 078}