How do I make a JTable column size exactly (or closely) fit contents?

后端 未结 1 773
野的像风
野的像风 2021-01-21 04:43

The output from my program is in a JTextArea inside a JScrollPane. It looks nasty:

Created BinaryTree.java      in     I:\\Netbeans OLD         


        
相关标签:
1条回答
  • 2021-01-21 05:05

    Check out the Table Column Adjuster.

    You can set the column width based on:

    1. the heading of the column
    2. the data in each row of the column
    3. the larger of the heading or data

    The class also supports other features to allow for dynamic resizing if the data is changed.

    Or you can use the basic code provided which just uses the prepareRenderer(...) method of the JTable to determine the maximum width.

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

    Edit:

    I was hoping that knowing the font size and number of characters

    FontMetrics fm = table.getFontMetrics( table.getFont() );
    int charWidth = fm.stringWidth("a");
    System.out.println( charWidth );
    
    0 讨论(0)
提交回复
热议问题