[ Back | Previous | Next ]

How to resize a Table to the maximun width of a value in the Table?

Package:
javax.swing.table.*
Product:
Swing
Release:
1.0.x
Related Links:
AbstractTableModel
JTable
TableCellRenderer
TableColumn
Comment:
	int width = 0;
	for (java.util.Enumeration e = getTable().getColumnModel().getColumns(); e.hasMoreElements();) {
		TableColumn tc = (TableColumn) e.nextElement();
		tc.sizeWidthToFit();
		width = Math.max(width, tc.getWidth());
		int columnIndex = tc.getModelIndex();
		FontMetrics fm = getGraphics().getFontMetrics(getFont());
		for (int i = 0; getTable() != null && getTable().getModel() != null && i < getTable().getRowCount(); i++) {
			String str = null;
			try {
				//str = getTable().getModel().getValueAt(i, columnIndex).toString();
				Component c = getCellRenderer().getTableCellRendererComponent(getTable(), getTable().getModel().getValueAt(i, columnIndex), false, false, i, columnIndex);
				if (c instanceof JLabel) {
					str = ((JLabel) c).getText();
				} else {
					str = "";
				}
			} catch (Exception ee) {
				str = "";
			}
			System.out.println("-- width= " + fm.stringWidth(str) + ", " + str);
			width = Math.max(fm.stringWidth(str) + 10, width);
		}
	}
	for (java.util.Enumeration e = getTable().getColumnModel().getColumns(); e.hasMoreElements();)
		 ((TableColumn) e.nextElement()).setWidth(width);
1