How to resize JTable column to string length?

前端 未结 3 1263
情话喂你
情话喂你 2020-12-03 06:08

I have a JTable that will have the last column data field change to different string values. I want to resize the column to the string length. What is the formula for string

相关标签:
3条回答
  • 2020-12-03 06:34

    This method will pack a given column in a JTable -

    /**
     * Sets the preferred width of the visible column specified by vColIndex. The column
     * will be just wide enough to show the column head and the widest cell in the column.
     * margin pixels are added to the left and right
     * (resulting in an additional width of 2*margin pixels).
     */ 
    public static void packColumn(JTable table, int vColIndex, int margin) {
        DefaultTableColumnModel colModel = (DefaultTableColumnModel)table.getColumnModel();
        TableColumn col = colModel.getColumn(vColIndex);
        int width = 0;
    
        // Get width of column header
        TableCellRenderer renderer = col.getHeaderRenderer();
        if (renderer == null) {
            renderer = table.getTableHeader().getDefaultRenderer();
        }
        java.awt.Component comp = renderer.getTableCellRendererComponent(
            table, col.getHeaderValue(), false, false, 0, 0);
        width = comp.getPreferredSize().width;
    
        // Get maximum width of column data
        for (int r=0; r<table.getRowCount(); r++) {
            renderer = table.getCellRenderer(r, vColIndex);
            comp = renderer.getTableCellRendererComponent(
                table, table.getValueAt(r, vColIndex), false, false, r, vColIndex);
            width = Math.max(width, comp.getPreferredSize().width);
        }
    
        // Add margin
        width += 2*margin;
    
        // Set the width
        col.setPreferredWidth(width);
    }
    
    0 讨论(0)
  • 2020-12-03 06:37

    you are not really interested in the string length (nor its mapping to a particular font/metrics). You're interested in the preferredSize of the renderingComponent which renderers the cell content. To get that, loop through all rows and query the size, something like

     int width = 0;
     for (row = 0; row < table.getRowCount(); row++) {
         TableCellRenderer renderer = table.getCellRenderer(row, myColumn);
         Component comp = table.prepareRenderer(renderer, row, myColumn);
         width = Math.max (comp.getPreferredSize().width, width);
     }
    

    Or use JXTable (in the SwingX project): it has a method pack() which does the work for you :-)

    Edit: the reason to prefer the table's prepareRenderer over manually calling getXXRendererComponent on the renderer is that the table might do decorate visual properties of the renderingComponent. If those decorations effect the prefSize of the component, a manual config is off.

    0 讨论(0)
  • 2020-12-03 06:37

    Table Column Adjuster works both statically and dynamically and the user can control this.

    0 讨论(0)
提交回复
热议问题