Java 如何获得正确的JTable宽度?

Java 如何获得正确的JTable宽度?,java,swing,jtable,Java,Swing,Jtable,我想要一张桌子的宽度。我尝试使用以下代码执行此操作: private static class ListenerForOk implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub handle(); if (!dataIsNotInput()) {

我想要一张桌子的宽度。我尝试使用以下代码执行此操作:

private static class ListenerForOk implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        handle();
        if (!dataIsNotInput()) {
            createDataTab();
            System.out.println(table.getWidth());
        }
    }
    double sum = 0.0;
    for (int i = 0; i < table.getColumnCount(); i++) {
        sum += table.getColumnModel().getColumn(i).getWidth();
    }
    System.out.println("sum: " + sum);
方法
createDataTab()
完成了添加JTable的所有工作。因此,在
createDataTab()之后我的桌子位于框架上,我可以看到它。但是这个代码
table.getWidth()
返回零。我尝试使用以下代码获取表格宽度的另一种方法:

private static class ListenerForOk implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        handle();
        if (!dataIsNotInput()) {
            createDataTab();
            System.out.println(table.getWidth());
        }
    }
    double sum = 0.0;
    for (int i = 0; i < table.getColumnCount(); i++) {
        sum += table.getColumnModel().getColumn(i).getWidth();
    }
    System.out.println("sum: " + sum);
因此,如果我在任何列中输入一个长字符串,该列将相应地展开,其中包含文本。我这样做了,专栏也扩大了。但在此之后,方法
table.getColumnModel().getColumn(i).getWidth()再次为所有列返回75。那么,如何获得正确的表宽度。

public int countTableWidth(JTable-aTable){
public int countTableWidth(JTable aTable) {
    int tableWidth = 0;
    Dimension cellSpacing = aTable.getIntercellSpacing();
    int columnCount = aTable.getColumnCount();
    int columnWidth[] = new int[columnCount];
    for (int i = 0; i < columnCount; i++) {
        columnWidth[i] = getMaxColumnWidth(aTable, i, true);

        tableWidth += columnWidth[i];
    }

    // account for cell spacing too
    tableWidth += ((columnCount - 1) * cellSpacing.width);
    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
 * @returns The table width, just in case the caller wants it...
 */
public static int getMaxColumnWidth(JTable aTable, int columnNo,
        boolean includeColumnHeaderWidth) {
    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;
}
int tableWidth=0; 维度cellSpacing=aTable.getIntercellSpacing(); int columnCount=aTable.getColumnCount(); int columnWidth[]=新的int[columnCount]; 对于(int i=0;i
调整列宽的基本代码是:

JTable table = new JTable( ... );
table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );

for (int column = 0; column < table.getColumnCount(); column++)
{
    TableColumn tableColumn = table.getColumnModel().getColumn(column);
    int preferredWidth = tableColumn.getMinWidth();
    int maxWidth = tableColumn.getMaxWidth();

    for (int row = 0; row < table.getRowCount(); row++)
    {
        TableCellRenderer cellRenderer = table.getCellRenderer(row, column);
        Component c = table.prepareRenderer(cellRenderer, row, column);
        int width = c.getPreferredSize().width + table.getIntercellSpacing().width;
        preferredWidth = Math.max(preferredWidth, width);

        //  We've exceeded the maximum width, no need to check other rows

        if (preferredWidth >= maxWidth)
        {
            preferredWidth = maxWidth;
            break;
        }
    }

    tableColumn.setPreferredWidth( preferredWidth );
}
JTable表=新的JTable(…);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
for(int column=0;column