Packing a Column of a JTable Component according to the row data
import java.awt.Component;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
public class Main {
public Main() {
JTable table = new JTable(3, 3);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
for (int i = 0; i < table.getColumnCount(); i++) {
DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
TableColumn col = colModel.getColumn(i);
int width = 0;
TableCellRenderer renderer = col.getHeaderRenderer();
for (int r = 0; r < table.getRowCount(); r++) {
renderer = table.getCellRenderer(r, i);
Component comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, i),
false, false, r, i);
width = Math.max(width, comp.getPreferredSize().width);
}
col.setPreferredWidth(width + 2);
}
JFrame f = new JFrame();
f.add(new JScrollPane(table));
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] argv) {
new Main();
}
}
Related examples in the same category