1 /*
2 * Copyright 2006-2016 The JGUIraffe Team.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License")
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package net.sf.jguiraffe.gui.platform.swing.builder.components.table;
17
18 import javax.swing.JTable;
19 import javax.swing.SwingUtilities;
20 import java.awt.Component;
21
22 /**
23 * <p>
24 * A helper class for setting the correct row heights for a Swing table.
25 * </p>
26 * <p>
27 * Swing does not automatically adapt the height of a table's rows to the size
28 * of the contained components. This is problematic especially if a custom cell
29 * renderer is used. This class implements this functionality. It can be called
30 * with a table as argument and then updates the heights of all rows so that the
31 * column with the greatest height fits in.
32 * </p>
33 *
34 * @author Oliver Heger
35 * @version $Id$
36 * @since 1.3
37 */
38 public class SwingTableRowHeightUpdater
39 {
40 /**
41 * Updates the heights of all rows in the specified table.
42 *
43 * @param table the table
44 */
45 public void updateRowHeights(JTable table)
46 {
47 updateRowHeights(table, 0, table.getRowCount() - 1);
48 }
49
50 /**
51 * Updates the heights of all rows of the specified table in the given
52 * range. Note that this obviously has to be done in a separate task in the
53 * event queue; otherwise, row height updates do not have any effect.
54 *
55 * @param table the table
56 * @param startRow the index of the first row
57 * @param endRow the index of the last row (including)
58 */
59 public void updateRowHeights(final JTable table, final int startRow,
60 final int endRow)
61 {
62 SwingUtilities.invokeLater(new Runnable()
63 {
64 public void run()
65 {
66
67 for (int row = startRow; row <= endRow; row++)
68 {
69 int rowHeight = table.getRowHeight(row);
70 for (int col = 0; col < table.getColumnCount(); col++)
71 {
72 Component component =
73 table.prepareRenderer(
74 table.getCellRenderer(row, col), row,
75 col);
76 rowHeight =
77 Math.max(rowHeight,
78 component.getPreferredSize().height);
79 }
80 table.setRowHeight(row, rowHeight);
81 }
82 }
83 });
84 }
85 }