Java Reference
In-Depth Information
frame.dispose();
}
}
Custom Layout Managers
Although the PDAP AWT subset contains all AWT layout managers including the flexible
GridBagLayout , there may still be cases that cannot be handled by the standard layout managers.
Although nesting panels with different layout managers helps in many situations, this approach isn't
suitable for all scenarios and is also very resource consuming. Thus, the design of custom layout
managers, generating application dependent layouts, is of special importance for developing PDAP
applications.
If we look back to the DialogMenuDemo application created in the section " Dialogs and Menus ," the
amounts and items are arranged using a GridLayout . Thus, the horizontal space is equally
distributed to both columns regardless of their actual size. Using a GridBagLayout , it would be
possible to distribute the space in a more flexible way. However, here you will learn the creation of
custom layout managers by the example of a layout manager similar to GridLayout , but allowing
different column widths and row heights. Because the layout is similar to the layout policy of HTML
tables, this layout manager is called TableLayout .
The first step of creating a custom layout manager is to implement the LayoutManager interface,
consisting of the methods listed in Table 4.3 . Those methods are responsible for the interaction of the
layout and the container it is assigned to.
Table 4.3. Methods of the LayoutManager Interface
Method
Description
void addLayoutComponent (String
constraint, Component comp)
Adds the specified component with the
specified constraint to the layout.
void layoutContainer (Container parent) Lays out the contents of the given
container.
Dimension minimumLayoutSize (Container
parent)
Calculates the minimum size
dimensions for the specified container.
Dimension preferredLayoutSize
(Container parent)
Calculates the preferred size for the
specified container.
void removeLayoutComponent (Component
c omp)
Removes the specified component from
the layout.
In addition to the LayoutManager interface methods, the TableLayout needs a constructor. The
TableLayout constructor takes the number of columns as parameter and stores it in the cols object
variable. The number of rows isn't required because it can be calculated by dividing the total number of
components by the number of columns. The following code snippet shows the TableLayout
constructor and a helper method for calculating the row count:
public TableLayout (int cols) {
this.cols = cols;
if (cols < 1)
throw new RuntimeException
("cols must be > 0");
}
int getRowCount (Container container) {
return (container.getComponentCount() + cols - 1) / cols;
}
 
 
Search WWH ::




Custom Search