基于JTable的列宽与内容自适应的实现方法
jtable默认的各列宽度平均,下函数可以实现各列宽度与内容长度适应!
public void fittablecolumns(jtable mytable){
jtableheader header = mytable.gettableheader();
int rowcount = mytable.getrowcount();
enumeration columns = mytable.getcolumnmodel().getcolumns();
while(columns.hasmoreelements()){
tablecolumn column = (tablecolumn)columns.nextelement();
int col = header.getcolumnmodel().getcolumnindex(column.getidentifier());
int width = (int)mytable.gettableheader().getdefaultrenderer()
.gettablecellrenderercomponent(mytable, column.getidentifier()
, false, false, -1, col).getpreferredsize().getwidth();
for(int row = 0; row<rowcount; row++){
int preferedwidth = (int)mytable.getcellrenderer(row, col).gettablecellrenderercomponent(mytable,
mytable.getvalueat(row, col), false, false, row, col).getpreferredsize().getwidth();
width = math.max(width, preferedwidth);
}
header.setresizingcolumn(column); // 此行很重要
column.setwidth(width+mytable.getintercellspacing().width);
}
使用方法:fittablecolumns(yourtablename);