JTable调整列宽

1。//   取得列幅的最大值
    private   int   getPreferredWidthForCloumn(JTable   table,int   icol){

        TableColumnModel   tcl   =   table.getColumnModel();
        TableColumn   col   =   tcl.getColumn(icol);
        int   c   =   col.getModelIndex(),width   =   0,maxw   =   0;

        for(int   r=0;r <table.getRowCount();++r){

            TableCellRenderer   renderer   =   table.getCellRenderer(r,c);
            Component   comp   =   renderer.getTableCellRendererComponent(table,table.getValueAt(r,c),false,false,r,c);
            width   =   comp.getPreferredSize().width;
            maxw   =   width   >   maxw?width:maxw;
        }

2。自动设定列的宽度

        // 设定每列的宽度为当列的最大的宽度。
        for(int   i=   0;   i <table.getColumnCount();   i++){
            int   with   =   this.getPreferredWidthForCloumn(table,i)   +   10;
            with   =   iniCW[i]   >   with   ?   iniCW[i]   :   with;
            table.getColumnModel().getColumn(i).setPreferredWidth(with);
        }
posted @ 2011-12-28 16:01  规格严格-功夫到家  阅读(676)  评论(0编辑  收藏  举报