01: package net.sourceforge.squirrel_sql.plugins.oracle.common;
02:
03: /*
04: * Copyright (C) 2004 Jason Height
05: * jmheight@users.sourceforge.net
06: *
07: * This library is free software; you can redistribute it and/or
08: * modify it under the terms of the GNU Lesser General Public
09: * License as published by the Free Software Foundation; either
10: * version 2.1 of the License, or (at your option) any later version.
11: *
12: * This library is distributed in the hope that it will be useful,
13: * but WITHOUT ANY WARRANTY; without even the implied warranty of
14: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15: * Lesser General Public License for more details.
16: *
17: * You should have received a copy of the GNU Lesser General Public
18: * License along with this library; if not, write to the Free Software
19: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20: */
21: import javax.swing.JTable;
22: import javax.swing.table.TableModel;
23: import javax.swing.table.TableCellRenderer;
24: import javax.swing.table.TableColumn;
25: import javax.swing.table.TableColumnModel;
26:
27: public class AutoWidthResizeTable extends JTable {
28:
29: public AutoWidthResizeTable() {
30: super ();
31: }
32:
33: public AutoWidthResizeTable(TableModel model) {
34: super (model);
35: }
36:
37: /** This method resizes the width of each column based on the data content.
38: * For large number of rows this is probably quite slow.
39: */
40: public void resizeColumnWidth() {
41: resizeColumnWidth(-1);
42: }
43:
44: public void resizeColumnWidth(int maxCellWidth) {
45: TableModel tm = getModel();
46: TableColumnModel colModel = getColumnModel();
47:
48: for (int col = tm.getColumnCount() - 1; col >= 0; col--) {
49: TableColumn column = colModel.getColumn(col);
50: TableCellRenderer renderer = column.getHeaderRenderer();
51: if (renderer == null) {
52: renderer = getTableHeader().getDefaultRenderer();
53: }
54: //Set the cell Width to the width of the header
55: int cellWidth = renderer.getTableCellRendererComponent(
56: this , column.getHeaderValue(), false, false, -1,
57: col).getPreferredSize().width;
58:
59: renderer = getDefaultRenderer(tm.getColumnClass(col));
60:
61: for (int row = tm.getRowCount() - 1; row >= 0; row--) {
62: int tmpWidth = renderer.getTableCellRendererComponent(
63: this , tm.getValueAt(row, col), false, false,
64: row, col).getPreferredSize().width;
65: if (tmpWidth > cellWidth)
66: cellWidth = tmpWidth;
67: }
68: //For reasons that i cannot exmplain, this is out by two, probably due to the
69: //border or insets around a cell??
70: cellWidth += 2;
71: if ((maxCellWidth != -1) && (cellWidth > maxCellWidth))
72: cellWidth = maxCellWidth;
73: column.setPreferredWidth(cellWidth);
74: }
75: }
76:
77: }
|