HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

"Creating a Custom Layout Manager"
Volume: 3 Issue: 10, p. 8

	

Listing 1:LocationManager.java code.
 
1  public interface LocationManager{ 
2    public final static int TOPLEFT = 0; 
3    public final static int TOPCENTER = 1; 
4    public final static int TOPRIGHT = 2; 
5    public final static int LEFT = 3; 
6    public final static int CENTER = 4; 
7    public final static int RIGHT = 5; 
8    public final static int BOTTOMLEFT = 6; 
9    public final static int BOTTOMCENTER = 7; 
10   public final static int BOTTOMRIGHT = 8; 
11 } 

Listing 2:CellConstraints.java code.
 
1  import java.awt.*; 
2 
3  class CellConstraints implements java.io.Serializable{ 
4 
5      protected int CellNum = -1; 
6      protected Point StartPoint = null; 
7      protected int Location = -1; 
8      protected int ColSpan = -1; 
9      protected int RowSpan = -1; 
10 
11    CellConstraints(int cell_num, int loc){ 
12       CellNum = cell_num; 
13       Location = loc; 
14    } 
15 
16    CellConstraints(int cell_num, int colspan, 
17                    int rowspan, Point loc){ 
18      CellNum = cell_num; 
19      ColSpan = colspan; 
20      RowSpan = rowspan; 
21      StartPoint = loc; 
22    } 
23 
24    CellConstraints(int cell_num, int colspan, 
25                    int rowspan, int loc){ 
26      CellNum = cell_num; 
27      ColSpan = colspan; 
28      RowSpan = rowspan; 
29      Location = loc; 
30    } 
31 
32    CellConstraints(int cell_num, int colspan, int rowspan){ 
33      CellNum = cell_num; 
34      ColSpan = colspan; 
35      RowSpan = rowspan; 
36    } 
37  } 

Listing 3: AddCompPanel.createPanel() code.
 
1   private void createPanel(){ 
2 
3     Font display_font = new Font("Helvetica", Font.BOLD, 14); 
4 
5     // Create the LayoutManager and set up this panel's basics. 
6     RelationalGridLayout layout_mgr = 
                new RelationalGridLayout(getSize(), 8, 8); 
7     setLayout(layout_mgr); 
8     setBackground(Color.black); 
9 
10    // Create the Purple Panel 
11    Panel purple_panel = new Panel(); 
12    purple_panel.setBackground(new Color(136,127,175)); 
13    purple_panel.setSize(layout_mgr.calcArea(8,2,-10)); 
                // layout_mgr.calcArea takes 8 cols, 2 rows, 10 pixel inset 
14 
15    // Create the Instruction Line 
16    Label instruct = new Label("Select the new component's 
                characteristics.", Label.CENTER); 
17    instruct.setSize(layout_mgr.calcArea(6,2,-10)); 
18    instruct.setForeground(Color.white); 
19    instruct.setBackground(new Color(136,127,175)); 
20    instruct.setFont(display_font); 
21 
22    // Create Long Blue Side Bar Panel. 
23    Panel side_bar = new Panel(); 
24    side_bar.setBackground(new Color(192,230,247)); 
25    side_bar.setSize(layout_mgr.calcArea(2,8)); 
                // layout_mgr.calcArea takes 2 cols, 8 rows, no inset. 
26 
27    // Create Shape, Size, Color, and Cell No. Fields and Labels 
28    Dimension field_size = layout_mgr.calcArea(2,1,-10); 
29 
30    // Shape: 
31    Label shape_label = new Label("Shape", Label.CENTER); 
32    shape_label.setFont(display_font); 
33    shape_label.setSize(field_size); 
34    shape_label.setBackground(new Color(192,230,247)); 
35 
36    shape = new Choice(); 
37    shape.setSize(field_size); 
38    shape.addItem("Square"); 
39    shape.addItem("Tall Rectangle"); 
40    shape.addItem("Long Rectangle"); 
41 
42    // Size: 
43    Label size_label = new Label("Size", Label.CENTER); 
44    size_label.setFont(display_font); 
45    size_label.setSize(field_size); 
46    size_label.setForeground(Color.white); 
47 
48    size = new Choice(); 
49    size.setBackground(Color.white); 
50    size.setSize(field_size); 
51    size.addItem("Small"); 
52    size.addItem("Medium"); 
53    size.addItem("Large"); 
54 
55    // Color: 
56    Label color_label = new Label("Color", Label.CENTER); 
57    color_label.setFont(display_font); 
58    color_label.setSize(field_size); 
59    color_label.setForeground(Color.white); 
60 
61    color = new Choice(); 
62    color.setBackground(Color.white); 
63    color.setSize(field_size); 
64    color.addItem("Red"); 
65    color.addItem("Black"); 
66    color.addItem("Blue"); 
67    color.addItem("Green"); 
68    color.addItem("Yellow"); 
69 
70    // Cell No.: 
71    Label cell_id_label = new Label("Cell No.", Label.CENTER); 
72    cell_id_label.setFont(display_font); 
73    cell_id_label.setSize(field_size); 
74    cell_id_label.setForeground(Color.white); 
75 
76    cell_id = new TextField("0"); 
77    cell_id.setBackground(Color.white); 
78    cell_id.setSize(35,30);  // Limit input to two numbers. 
79    cell_id.setEditable(true); 
80 
81    // Create Name Label and Field 
82    Label comp_label = new Label("Component's ", Label.RIGHT); 
83    comp_label.setFont(display_font); 
84    comp_label.setBackground(new Color(192,230,247)); 
85    Dimension comp_label_size = layout_mgr.calcArea(2,1,-10); 
86    comp_label.setSize(comp_label_size); 
87 
88    Label name_label = new Label("Name:", Label.CENTER); 
89    name_label.setFont(display_font); 
90    name_label.setForeground(Color.white); 
91    name_label.setSize(layout_mgr.calcArea(1,1,-10)); 
92 
93    comp_name = new TextField(DEFUALT_NAME); 
94    comp_name.setBackground(Color.white); 
95    comp_name.setEditable(true); 
96    Dimension name_field_size = layout_mgr.calcArea(5,1,-10); 
97    comp_name.setSize(name_field_size); 
98 
99    // Create Add Button 
100   Button add_button = new Button("Add"); 
101   add_button.addActionListener(panel_controller); 
102   add_button.setForeground(Color.black); 
103   add_button.setSize(field_size); 
104 
105   // Add Components to this Panel. 
106   // First three additions are to cell ID 0, each overlapping the other. 
107   add(side_bar, new CellConstraints(0,2,8,LocationManager.CENTER),0); 
108   add(purple_panel, new CellConstraints(0,8,2, 
                LocationManager.CENTER),0); 
109   add(instruct, new CellConstraints(0,8,2,LocationManager.CENTER),0); 
110 
111   add(shape_label, new CellConstraints(16,2,1, 
                LocationManager.BOTTOMCENTER),0); 
112   add(shape, new CellConstraints(24,2,1, LocationManager.TOPCENTER),0); 
113 
114   add(size_label, new CellConstraints(18,2,1, 
                LocationManager.BOTTOMCENTER),0); 
115   add(size, new CellConstraints(26,2,2, LocationManager.TOPCENTER),0); 
116 
117   add(color_label, new CellConstraints(20,2,1, 
                LocationManager.BOTTOMCENTER),0); 
118   add(color, new CellConstraints(28,2,1, LocationManager.TOPCENTER),0); 
119 
120   add(cell_id_label, new CellConstraints(22,2,1, 
                LocationManager.BOTTOMCENTER),0); 
121   add(cell_id, new CellConstraints(30,2,1, 
                LocationManager.TOPCENTER),0); 
122 
123   add(comp_label, new CellConstraints(32,2,2, LocationManager.RIGHT),0); 
124   add(name_label, new CellConstraints(34,1,2, LocationManager.LEFT),0); 
125 
126   add(comp_name, new CellConstraints(35,5,2,LocationManager.LEFT),0); 
127   add(add_button, new CellConstraints(54,2,2,LocationManager.CENTER),0); 
128 
129   doLayout(); 
130  } 

Listing 1
 
1   import java.awt.*; 
2   import java.util.Hashtable; 
3   import java.lang.Math; 
4   import LocationManager; 
5   import CellConstraints; 
6 
7   class ItemInfo implements java.io.Serializable{ 
8     double yratio = 0.0; // Row 
9     double xratio = 0.0; // Column 
10    double wratio = 0.0; // Item's width 
11    double hratio = 0.0; // Item's height 
12 
13    ItemInfo(double x, double y, double w, double h){ 
14      wratio = w; 
15      hratio = h; 
16      xratio = x; 
17      yratio = y; 
18    }  // Empty Constructor. 
19  } 
20 
21  public class RelationalGridLayout implements LayoutManager2, 
22            LocationManager, java.io.Serializable{ 
23 
24    // For the Grid 
25    protected int NumOfCols = 0;  // Number of columns in the grid. 
26    protected int NumOfRows = 0;  // Number of rows in the grid. 
27    protected Dimension CellSize = null; // The size of each cell. 
28    protected Dimension PanelSize = null; 
29    protected int CellSpacing = 0; 
30    protected int DefaultCellSpacing = 0; 
31 
32    protected Hashtable ComponentInfo = null; 
33 
34    // Constructor 
35    public RelationalGridLayout(Dimension size, int cols, int rows){ 
36      NumOfCols = cols; 
37      NumOfRows = rows; 
38      PanelSize = size; 
39      CellSize = calcCellSize(size); 
40      ComponentInfo = new Hashtable(); 
41    } 
42 
43    // Required Methods But Not Used 
44    public void addLayoutComponent(String name, Component comp){} 
45    public void invalidateLayout(Container target){} 
46    public float getLayoutAlignmentX(Container target){return 0.5f;} 
47    public float getLayoutAlignmentY(Container target){return 0.5f;} 
48    public Dimension maximumLayoutSize(Container target){return null;} 
49    public Dimension minimumLayoutSize(Container 
            target){return(target.getSize());} 
50    public Dimension preferredLayoutSize(Container 
            target){return(target.getSize());} 
51 
52    // Public Methods 
53    public Dimension calcArea(int cols, int rows, int padding){ 
54      Dimension size = new Dimension(getCellSize()); 
55      size.width = (size.width * cols) + padding; 
56      size.height = (size.height * rows) + padding; 
57      return(size); 
58    } 
59 
60    public Dimension calcArea(int cols, int rows){ 
61      return(calcArea(cols, rows, 0)); 
62    } 
63 
64    public Dimension getCellSize(){ // Get copy of cell's size. 
65      return(new Dimension(CellSize)); 
66    } 
67 
68    public int getCellSpacing(){ // Get the default spacing for the cell. 
69      return(CellSpacing); 
70    } 
71 
72    public void setCellSpacing(int i){ 
73      // Set spacing amount between component and cell edges. 
74      CellSpacing = i; 
75    } 
76 
77    public void resetCellSpacing(){ 
78      CellSpacing = DefaultCellSpacing; 
79    } 
80 
81    public void addLayoutComponent(Component comp, Object obj){ 
82      Insets insets = null; 
83      Point p = null; 
84      CellConstraints constraints = null; 
85 
86      // Cast the object to the correct type. 
87      if(obj instanceof CellConstraints){ 
88        constraints = (CellConstraints) obj; 
89      } 
90 
91      Dimension item_size = comp.getSize();  // Get the size of the item. 
92 
93      // Calculate point within container that the item is to be placed. 
94      if((constraints.ColSpan != -1) && (constraints.RowSpan != -1)){ 
95        if(constraints.StartPoint != null){ 
96          insets = calcCellInset(constraints.StartPoint, 
                  calcCellSize(constraints.ColSpan, constraints.RowSpan), 
                  item_size); 
97        }else if(constraints.Location > -1){ 
98          insets = calcInsets(constraints.Location, constraints.ColSpan, 
                 constraints.RowSpan, item_size); 
99        }else{ 
100         insets = calcInsets(CENTER, constraints.ColSpan, 
                 constraints.RowSpan, item_size); 
101       } 
102       // Convert cell_num to cell's x/y coordinate. 
103       p = calcStartPoint(constraints.CellNum, insets); 
104     }else{ 
105       if(constraints.CellNum != -1){ 
106         int cols = item_size.width/CellSize.width; 
107         int rows = item_size.height/CellSize.height; 
108         insets = calcInsets(CENTER, cols, rows, item_size); 
109         p = calcStartPoint(constraints.CellNum, insets); 
110       } 
111     } 
112 
113     // Create the proportional size and location for the component. 
114     // Get x, y, width and height's relationship to container's. 
115     double x = calcWidthRatio(p.x); 
116     double y = calcHeightRatio(p.y); 
117     double w = calcWidthRatio(item_size.width); 
118     double h = calcHeightRatio(item_size.height); 
119 
120     // Add the cell info to the hashtable. 
121     ComponentInfo.put(comp,new ItemInfo(x,y,w,h)); 
122   } 
123 
124   public void removeLayoutComponent(Component comp){ 
125     // Remove the component's info from hashtable. 
126     if(ComponentInfo.containsKey(comp)){ 
127       ComponentInfo.remove(comp); 
128     } 
129   } 
130 
131   public void layoutContainer(Container target){ 
132     ItemInfo cell; 
133     int x,y,w,h; 
134 
135     Dimension size = target.getSize(); 
136     if((PanelSize.width != size.width) || 
           (PanelSize.height != size.height)){ // Size may have changed. 
137       PanelSize = size; 
138       CellSize = calcCellSize(size); 
139    } 
140 
141     if(! ComponentInfo.isEmpty()){ 
142       Component[] comps = target.getComponents(); 
143       for(int i=0; i < comps.length; i++){ 
144         if(ComponentInfo.containsKey(comp)){ 
145           cell = (ItemInfo) ComponentInfo.get(comps[i]); 
146           // Convert relational values to real values 
147           x = (int) Math.round(size.width * cell.xratio); 
148           y = (int) Math.round(size.height * cell.yratio); 
149           w = (int) Math.round(size.width * cell.wratio); 
150           h = (int) Math.round(size.height * cell.hratio); 
151           comps[i].setBounds(x,y,w,h); 
152         } 
153       } 
154     } 
155   } 
156 
157   // Private & Protected Methods 
158   private double calcWidthRatio(int w){ 
159     return((double) w/PanelSize.width); 
160   } 
161 
162   private double calcHeightRatio(int h){ 
163     return((double) h/PanelSize.height); 
164   } 
165 
166   private Dimension calcCellSize(Dimension size){ 
167     int w = (int) Math.round((float) size.width/NumOfCols); 
168     int h = (int) Math.round((float) size.height/NumOfRows); 
169     return(new Dimension(w, h)); 
170   } 
171 
172   private Dimension calcCellSize(int colspan, int rowspan){ 
173     // Calculates the size of a cell given the colspan and rowspan. 
174     Dimension cell_size = new Dimension(CellSize); 
175     cell_size.width *= colspan; 
176     cell_size.height *= rowspan; 
177     return(cell_size); 
178   } 
179 
180   private int calcCellNum(int col, int row){ 
181     int cell_num = (NumOfCols * row) + col; 
182     return(cell_num); 
183   } 
184 
185   private Insets calcCellInset(Point p, Dimension cell_size, 
              Dimension item_size){ 
186     // Calculates the insets from a point given the size of an object. 
187    int left = p.x; 
188    int top = p.y; 
189    int right = cell_size.width - (p.x + item_size.width); 
190     int bottom = cell_size.height - (p.y + item_size.height); 
191     return(new Insets(top,left,bottom,right)); 
192   } 
193 
194   private Point calcStartPoint(int cell_num, Insets insets){ 
195     int row = cell_num/NumOfCols;  // row number. 
196     int col = (cell_num - (row * NumOfCols)); // column number. 
197     row = (row * CellSize.height) + insets.top; 
198     col = (col * CellSize.width) + insets.left; 
199     return(new Point(col,row)); 
200   } 


 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.