Search code examples
javaswingjtablecolumn-width

setting a prototype value (for auto-width calculation) of a JTable column


either this doesn't exist, or I'm not thinking/searching correctly because it's late...

I want to set a JTable column width in Swing based on a prototype value for the largest string I expect (or know) to exist in a particular column. I don't know the # of pixels since I don't necessarily know the font at compile time.

Is there a way to set a prototype value for column width purposes, the way there is for row height purposes? If so, how?


Solution

  • Have you tried creating a JLabel at run time and using its size to resize your table?

    // create a label that will be using the run-time font
    JLabel prototypeLabel = new JLabel("Not Applicable")
    
    // get the labels preferred sizes
    int preferredWidth = prototypeLabel.getPreferredSize().getWidth();
    int preferredHeight = prototypeLabel.getPreferredSize().getHeight();
    
    // set the sizes of the table's row and columns
    myTable.setRowHeight(preferredHeight);
    
    for(TableColumn column : myTable.getColumnModel.getColumns()){
       column.setPreferredWidth(preferredWidth);        
    }