Auto Resize JTable Columns


This class auto resizes columns of a JTable, maximizing any non-used width columns and transferring those extra widths to other columns. This way, a column with a JCheckBox will have a width almost equal to that of a JCheckBox‘s width. The class TableColumnResizer contains one static method and you can pass the JTable object as the parameter. The code does the rest.

To use the method, do this:

1
TableColumnResizer.adjustColumnPreferredWidths(myJTableObject);

Here is the code of the TableColumnResizer class.

1
2
3
4
5
6
7
8
9
10
public class TableColumnResizer {
 
    public static void adjustColumnPreferredWidths(JTable table) {
        if (table == null || table.getColumnCount() == 0) return;
 
        // strategy - get max width for cells in column and
        // make that the preferred width
        TableColumnModel columnModel = table.getColumnModel();
 
        for (int col=0; col

Found this post useful? Buy me a cup of coffee or subscribe to my RSS feeds and Google Friend Connect

Related Posts with Thumbnails

3 Responses to “Auto Resize JTable Columns”

  1. 1
    rizky2009 Says:

    i like ur script, I tray now

  2. 2
    Magnolia Sivertsen Says:

    This is a good posting, I was wondering if I could use this summary on my website, I will link it back to your website though. If this is a problem please let me know and I will take it down right away.

  3. 3
    tech Says:

    no problem here at all ;)

Leave a Reply

Spam protection by WP Captcha-Free