![]() |
The Java Developers Almanac 1.4 |
|
e913. Setting the Height of a Row in a JTable ComponentThe height of a row in aJTable component is based on an assigned
value rather than on the preferred height of the renderers used in
that row. You can either set a default height for all rows or set the
heights for individual rows.
This example demonstrates a few routines that can be used to adjust the height of rows in applications where the row heights can vary. int rows = 10;
int cols = 5;
JTable table = new JTable(rows, cols);
// Set the 1st row to 60 pixels high
table.setRowHeight(0, 60);
// Set the height of all rows to 32 pixels high,
// regardless if any heights were assigned to particular rows
table.setRowHeight(32);
// the height of the 1st row is set to 32 pixels high
// Returns the preferred height of a row.
// The result is equal to the tallest cell in the row.
public int getPreferredRowHeight(JTable table, int rowIndex, int margin) {
// Get the current default height for all rows
int height = table.getRowHeight();
// Determine highest cell in the row
for (int c=0; c<table.getColumnCount(); c++) {
TableCellRenderer renderer = table.getCellRenderer(rowIndex, c);
Component comp = table.prepareRenderer(renderer, rowIndex, c);
int h = comp.getPreferredSize().height + 2*margin;
height = Math.max(height, h);
}
return height;
}
// The height of each row is set to the preferred height of the
// tallest cell in that row.
public void packRows(JTable table, int margin) {
packRows(table, 0, table.getRowCount(), margin);
}
// For each row >= start and < end, the height of a
// row is set to the preferred height of the tallest cell
// in that row.
public void packRows(JTable table, int start, int end, int margin) {
for (int r=0; r<table.getRowCount(); r++) {
// Get the preferred height
int h = getPreferredRowHeight(table, r, margin);
// Now set the row height using the preferred height
if (table.getRowHeight(r) != h) {
table.setRowHeight(r, h);
}
}
}
e908. Appending a Row to a JTable Component e909. Inserting a Row in a JTable Component e910. Removing a Row from a JTable Component e911. Moving a Row in a JTable Component e912. Copying a Row or Column in a JTable Component e914. Shading Rows and Columns in a JTable Component
© 2002 Addison-Wesley. |