调整JTable的单元格宽度

BWStatTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        for (int i = 0; i < BWStatTable.getColumnCount(); i++) {
            TableColumn tc = BWStatTable.getColumn(BWStatTable.
                    getColumnName(i));
            int c = tc.getModelIndex();
            int width = 0;
            int maxw = 0;
            for (int r = 0; r < BWStatTable.getRowCount(); ++r) {
                TableCellRenderer renderer = BWStatTable.
                                             getCellRenderer(r, c); //得到每个单元格的渲染器
                Component comp = renderer.getTableCellRendererComponent(
                        BWStatTable, "", false, false,
                        r, c);
                width = comp.getPreferredSize().width;
                maxw = width > maxw ? width : maxw;
            }
            TableCellRenderer headRenderer = tc.getHeaderRenderer(); //得到每列中的表头渲染器
            if (headRenderer == null) {
                headRenderer = BWStatTable.getTableHeader().         //得到表头中的表头渲染器
                               getDefaultRenderer();
            }
            Component comp = headRenderer.getTableCellRendererComponent(
                    BWStatTable, tc.getHeaderValue(), false, false, 0,
                    i);
            int w = comp.getPreferredSize().width;
            maxw = w > maxw ? w : maxw;
            if (BWStatTable.getColumnCount() == 2) {
                tc.setMinWidth(maxw + 20);
                tc.setPreferredWidth(maxw + 160);
            }
            if (BWStatTable.getColumnCount() == 3) {
                tc.setMinWidth(maxw + 20);                //列设置宽度
                tc.setPreferredWidth(maxw + 70);
            }
        }

 

你可能感兴趣的:(C++,c,C#)