JTable设置列宽以保留所有文本

时间:2015-11-30 07:59:25

标签: java swing jtable

好的,所以我在jscrollpane中有一个jtable。目前,列设置为最小宽度。如果容器太大而没有宽度来填充容器,它们会变得更宽。然而,他们不会缩小。告诉你我在说什么 Image 1 此表中的所有列标题和单元格值都可见。细胞宽度扩大以填充容器。调整大小后我们得到这个

image 2

此处列已减少到最小宽度,并且由于容器无法容纳它们,因此添加了所有滚动条。在第二张图片中,你可以看到标题" Vry长标题被刷掉了#34;和细胞标记"非常长的细胞数据"减少并替换为" ..."。我想要做的是将每列的最小列宽更改为足够长,以至于它永远不会切断表中的最新内容。这包括单元格值和标题。我只能找到人们询问其中一个而不是两个。这是我的相关代码。

co[0] = "Vry long title get smushed";
o[1][1] = "Very long cell data";
JTable table1 = new JTable(o, co)
        {
            public boolean getScrollableTracksViewportWidth()
            {
                return getPreferredSize().width < getParent().getWidth();
            }
        };  
    table1.getTableHeader().setReorderingAllowed(false);
    table1.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
    tablePane.setViewportView(table1);

2 个答案:

答案 0 :(得分:0)

我对JTables没有经验,但是,你试过这个吗?:

JFrame.pack();

答案 1 :(得分:0)

将此属性设置为表

setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

使用此实用程序类自动调整列

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.util.StringTokenizer;

import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.text.StyledDocument;
import javax.swing.text.View;

import org.apache.commons.lang.StringUtils;

public class AutofitTableColumns {

private static final int DEFAULT_COLUMN_PADDING = 5;

/*
 * @param JTable aTable, the JTable to autoresize the columns on
 * @param boolean includeColumnHeaderWidth, use the Column Header width as a minimum width
 * @returns The table width, just in case the caller wants it...
 */
public static int autoResizeTable(JTable aTable, boolean includeColumnHeaderWidth) {
    return (autoResizeTable(aTable, includeColumnHeaderWidth, DEFAULT_COLUMN_PADDING));
}

/*
 * @param JTable aTable, the JTable to autoresize the columns on
 * @param boolean includeColumnHeaderWidth, use the Column Header width as a minimum width
 * @param int columnPadding, how many extra pixels do you want on the end of each column
 * @returns The table width, just in case the caller wants it...
 */
public static int autoResizeTable(JTable aTable, boolean includeColumnHeaderWidth, int columnPadding) {
    int columnCount = aTable.getColumnCount();
    int tableWidth = 0;

    Dimension cellSpacing = aTable.getIntercellSpacing();

    if (columnCount > 0) // must have columns !
    {
        // STEP ONE : Work out the column widths

        int columnWidth[] = new int[columnCount];

        for (int i = 0; i < columnCount; i++) {
            columnWidth[i] = getMaxColumnWidth(aTable, i, true, columnPadding);

            tableWidth += columnWidth[i];
        }

        // account for cell spacing too
        tableWidth += ((columnCount - 1) * cellSpacing.width);

        // STEP TWO : Dynamically resize each column

        // try changing the size of the column names area
        JTableHeader tableHeader = aTable.getTableHeader();

        Dimension headerDim = tableHeader.getPreferredSize();

        // headerDim.height = tableHeader.getHeight();
        headerDim.width = tableWidth;
        tableHeader.setPreferredSize(headerDim);

        TableColumnModel tableColumnModel = aTable.getColumnModel();
        TableColumn tableColumn;

        for (int i = 0; i < columnCount; i++) {
            tableColumn = tableColumnModel.getColumn(i);

            tableColumn.setPreferredWidth(columnWidth[i]);
        }

    }

    return (tableWidth);
}

/*
 * @param JTable aTable, the JTable to autoresize the columns on
 * @param int columnNo, the column number, starting at zero, to calculate the maximum width on
 * @param boolean includeColumnHeaderWidth, use the Column Header width as a minimum width
 * @param int columnPadding, how many extra pixels do you want on the end of each column
 * @returns The table width, just in case the caller wants it...
 */
public static int getMaxColumnWidth(JTable aTable, int columnNo,
        boolean includeColumnHeaderWidth,
        int columnPadding) {
    TableColumn column = aTable.getColumnModel().getColumn(columnNo);
    Component comp = null;
    int maxWidth = 0;

    if (includeColumnHeaderWidth) {
        TableCellRenderer headerRenderer = column.getHeaderRenderer();
        if (headerRenderer != null) {
            comp = headerRenderer.getTableCellRendererComponent(aTable, column.getHeaderValue(), false, false, 0, columnNo);

            if (comp instanceof JTextComponent) {
                JTextComponent jtextComp = (JTextComponent) comp;

                String text = jtextComp.getText();
                Font font = jtextComp.getFont();
                FontMetrics fontMetrics = jtextComp.getFontMetrics(font);

                maxWidth = SwingUtilities.computeStringWidth(fontMetrics, text);
            } else {
                maxWidth = comp.getPreferredSize().width;
            }
        } else {
            try {
                String headerText = (String) column.getHeaderValue();
                JLabel defaultLabel = new JLabel(headerText);

                //Igor
                //ako je u table modelu kao ime kolone stvalje html code
                //treba izracunati max duzinu text na sljedeci nacin
                View view = (View) defaultLabel.getClientProperty("html");
                if (view != null) {
                    Document d = view.getDocument();
                    if (d instanceof StyledDocument) {
                        StyledDocument doc = (StyledDocument) d;
                        int length = doc.getLength();
                        headerText = StringUtils.leftPad("", length + DEFAULT_COLUMN_PADDING);
                    }
                }
                //END Igor

                Font font = defaultLabel.getFont();
                FontMetrics fontMetrics = defaultLabel.getFontMetrics(font);

                maxWidth = SwingUtilities.computeStringWidth(fontMetrics, headerText);
            } catch (ClassCastException ce) {
                // Can't work out the header column width..
                maxWidth = 0;
            }
        }
    }

    TableCellRenderer tableCellRenderer;
    // Component comp;
    int cellWidth = 0;

    for (int i = 0; i < aTable.getRowCount(); i++) {
        tableCellRenderer = aTable.getCellRenderer(i, columnNo);

        comp = tableCellRenderer.getTableCellRendererComponent(aTable, aTable.getValueAt(i, columnNo), false, false, i, columnNo);
        //textarea na prvo mjesto jer je takodjer descendant od JTextComponent
        if (comp instanceof JTextArea) {
            JTextComponent jtextComp = (JTextComponent) comp;

            String text = getMaximuWrapedString(jtextComp.getText());
            Font font = jtextComp.getFont();
            FontMetrics fontMetrics = jtextComp.getFontMetrics(font);

            int textWidth = SwingUtilities.computeStringWidth(fontMetrics, text);

            maxWidth = Math.max(maxWidth, textWidth);
        } else if (comp instanceof JTextComponent) {
            JTextComponent jtextComp = (JTextComponent) comp;

            String text = jtextComp.getText();
            Font font = jtextComp.getFont();
            FontMetrics fontMetrics = jtextComp.getFontMetrics(font);

            int textWidth = SwingUtilities.computeStringWidth(fontMetrics, text);

            maxWidth = Math.max(maxWidth, textWidth);
        } else {
            cellWidth = comp.getPreferredSize().width;

            // maxWidth = Math.max ( headerWidth, cellWidth );
            maxWidth = Math.max(maxWidth, cellWidth);
        }
    }

    return (maxWidth + 5 + columnPadding);
}

/**
 * racuna maximalnu duzinu najduzeg stringa wrapped texta
 *
 * @param str
 * @return
 */
private static String getMaximuWrapedString(String str) {
    StringTokenizer strT = new StringTokenizer(str, "\n");
    String max = "";
    String s = "";
    while (strT.hasMoreTokens()) {
        s = strT.nextToken();
        if (s.length() > max.length()) {
            max = s;
        }
    }
    return max;
}

}