How to get the minimum preferred width of the header component of a JTable column so it cannot be resized smaller than the value?

StackOverflow https://stackoverflow.com/questions/10807418

I am trying to prevent my JTable being re-sized in a way that the headers are smaller than the size of the text they hold. The problem I am having is that the minimum preferred width I am getting for each header component is only 10 which is obviously too small when the values in each header component are "Header 1", "Header 2", "Header 3" and so on.

I have spent a lot of time searching SO and tried implementing various suggestions, but haven't managed to come across a solution as of yet. Please see the current code I am using as apart of my extended JTable:

public class MyTable extends JTable {

private Map<Integer, Integer> minSizeMap;

public void calculateMinColumnSizes() {

    int width = 0;
    int row = 0;
    minSizeMap = new HashMap<Integer, Integer>();

    for (int column = 0; column < columnModel.getColumnCount(); column++) {
        TableColumn tableColumn = columnModel.getColumn(column);
        TableCellRenderer renderer = tableColumn.getCellRenderer();
        Component comp = this.prepareRenderer(renderer, row, column);
        width = Math.max(comp.getPreferredSize().width, width);
        minSizeMap.put(tableColumn.getModelIndex(), width);
    }
   }
}

The original code came from kleopatra's answer to How to resize JTable column to string length? ,but I have changed parts as at the moment I only want to get the minimum preferred width of each column header, and store it for later comparison after resizing.

All the models have been set before I call the method, so I'm a bit perplexed as to how it is getting 10 for the component preferred width, when the minWidth and preferredWidth defaults for TableColumn are 15 and 75 respectively.

Any ideas as to what I've done/understood wrong?

有帮助吗?

解决方案

I see several issues in your code:

  1. You don't use the Table header renderers, but the TableColumn cell renderers (they could be different)
  2. You test the preferred size for the first row, not the headers
  3. You use width = Math.max(comp.getPreferredSize().width, width); which simply does not make any sense

Here is a snippet that should get you going:


for (int column = 0; column < columnModel.getColumnCount(); column++) {
    TableColumn tableColumn = columnModel.getColumn(column);
    TableCellRenderer renderer = tableColumn.getHeaderRenderer();
    if (renderer == null) {
        renderer = getTableHeader().getDefaultRenderer();
    }
    Component component = renderer.getTableCellRendererComponent(this, 
             tableColumn.getHeaderValue(), false, false, -1, column);
    minSizeMap.put(tableColumn.getModelIndex(), component.getPreferredSize().width);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top