简体   繁体   中英

How can I get the correct JTable width?

I want to get a table width. I try to do it with this code:

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());
        }
    }

Method createDataTab() does all the work to add the JTable. So, after createDataTab(); my table lies on frame and I can see it. But this code table.getWidth() returns zero. Another way I try to get table width with this code:

    double sum = 0.0;
    for (int i = 0; i < table.getColumnCount(); i++) {
        sum += table.getColumnModel().getColumn(i).getWidth();
    }
    System.out.println("sum: " + sum);

The method table.getColumnModel().getColumn(i).getWidth() returns 75 for all columns. It is correct value and I have a correct table width. But in my class for table I override one method. Here is my code:

class MyTable extends JTable {

@Override
public Component prepareRenderer(TableCellRenderer renderer, int row,
        int column) {
    Component component = super.prepareRenderer(renderer, row, column);
    int rendererWidth = component.getPreferredSize().width;
    TableColumn tableColumn = getColumnModel().getColumn(column);
    tableColumn
            .setPreferredWidth(Math.max(rendererWidth
                    + getIntercellSpacing().width,
                    tableColumn.getPreferredWidth()));

    return component;
}

So, if I enter a long string in any column this column will expanded accordingly with text in it. I did it and the column was expanded. But after that the method table.getColumnModel().getColumn(i).getWidth(); returns 75 for all columns again. So, how can I get the correct table width.

The basic code for adjusting column widths is:

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 );
}

You can also check out Table Column Adjuster for a class that incorporates the above code and adds extra features like auto column adjustment as data is changed.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM