1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.gui.util;
|
---|
3 |
|
---|
4 | import java.awt.Component;
|
---|
5 |
|
---|
6 | import javax.swing.JTable;
|
---|
7 | import javax.swing.table.TableCellRenderer;
|
---|
8 |
|
---|
9 | /**
|
---|
10 | * The class that provide common JTable customization methods
|
---|
11 | */
|
---|
12 | public final class TableHelper {
|
---|
13 |
|
---|
14 | private TableHelper() {
|
---|
15 | // Hide default constructor for utils classes
|
---|
16 | }
|
---|
17 |
|
---|
18 | /**
|
---|
19 | * adjust the preferred width of column col to the maximum preferred width of the cells
|
---|
20 | * requires JTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
|
---|
21 | * @param tbl table
|
---|
22 | * @param col column index
|
---|
23 | * @param maxColumnWidth maximum column width
|
---|
24 | */
|
---|
25 | public static void adjustColumnWidth(JTable tbl, int col, int maxColumnWidth) {
|
---|
26 | int maxwidth = 0;
|
---|
27 | for (int row = 0; row < tbl.getRowCount(); row++) {
|
---|
28 | TableCellRenderer tcr = tbl.getCellRenderer(row, col);
|
---|
29 | Object val = tbl.getValueAt(row, col);
|
---|
30 | Component comp = tcr.getTableCellRendererComponent(tbl, val, false, false, row, col);
|
---|
31 | maxwidth = Math.max(comp.getPreferredSize().width, maxwidth);
|
---|
32 | }
|
---|
33 | tbl.getColumnModel().getColumn(col).setPreferredWidth(Math.min(maxwidth+10, maxColumnWidth));
|
---|
34 | }
|
---|
35 |
|
---|
36 | /**
|
---|
37 | * adjust the table's columns to fit their content best
|
---|
38 | * requires JTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
|
---|
39 | * @param tbl table
|
---|
40 | * @since 14476
|
---|
41 | */
|
---|
42 | public static void computeColumnsWidth(JTable tbl) {
|
---|
43 | for (int column = 0; column < tbl.getColumnCount(); column++) {
|
---|
44 | adjustColumnWidth(tbl, column, Integer.MAX_VALUE);
|
---|
45 | }
|
---|
46 | }
|
---|
47 | }
|
---|