3

I am running into a problem that has been discussed on here before: getting a JScrollPane containing a JTable to display the horizontal scrollbar as I desire. HERE is a post I tried following, but for some reason it does not seem to work with my situation (I think it is because I've set one of my columns to have a fixed width.

Here is a SSCCE:

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

@SuppressWarnings("serial")
public class TableScrollTest extends JFrame
{
    public TableScrollTest() {

        DefaultTableModel model = new DefaultTableModel(new Object[]{"key", "value"},0);
        model.addRow(new Object[]{"short", "blah"});
        model.addRow(new Object[]{"long", "blah blah blah blah blah blah blah"});

        JTable table = new JTable(model) {
            public boolean getScrollableTracksViewportWidth() {
                return getPreferredSize().width < getParent().getWidth();
            }
        };        
        table.getColumn("key").setPreferredWidth(60);
        table.getColumn("key").setMinWidth(60);
        table.getColumn("key").setMaxWidth(60);
        table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );

        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );
    }

    public static void main(String[] args) {
        TableScrollTest frame = new TableScrollTest();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setSize(200, 200);
        frame.setResizable(false);
        frame.setVisible(true);
    }
}

In short, I have a two column table for displaying key/value pairs. The container holding the table is of fixed width, and the first column of the table is also of fixed width (since I know how long all the key names will be). The second column will contain values of varying string length. A horizontal scrollbar should only appear when there are values present which are too long to fit in the width allotted for the column.

enter image description here

Because the second value above has such a long length, the scrollbar should be visible. However, it's not, and everything I have tried has only succeeded in getting it visible always, which is not what I want... I only want it visible if "long" values are present. It seems like the getScrollableTracksViewportWidth() method being overridden in the table constructor checks what the preferred width of the table is... so somehow I need to direct the table to prefer a larger width based on the contents of that second column only... but I'm stumped.

Any ideas?

Community
  • 1
  • 1
The111
  • 5,757
  • 4
  • 39
  • 55
  • 1
    You're immediate issue is because you've overridden `getScrollableTracksViewportWidth` which means that table can never be wider then the scroll pane... – MadProgrammer Feb 22 '13 at 01:07
  • @MadProgrammer Are you sure? The example I linked has that method overridden, and in that example, the table does get wider than the scroll pane. – The111 Feb 22 '13 at 01:11
  • 1
    But the preferredWidth of the table is based on the width of the `TableColumn` which does not take into account the width of the content, which means that unless you change the width of the second column the same way you changed the first, it will always return `true`. I removed the `getScrollableTracksViewportWidth` method and manually resized the column and was able to get the horizontal scroll bar to appear. – MadProgrammer Feb 22 '13 at 01:14
  • @MadProgrammer ok, I see what you're saying. It seems then that my goal is to force the cell renderer to automatically make cells fit long strings, so I don't have to manually resize it as you did above. – The111 Feb 22 '13 at 01:17

3 Answers3

7

This is a hackey solution

Basically, what it does is calculates the "preferred" width of all the columns based on the values from all the rows.

It takes into consideration changes to the model as well as changes to the parent container.

Once it's done, it checks to see if the "preferred" width is greater or less than the available space and sets the trackViewportWidth variable accordingly.

You can add in checks for fixed columns (I've not bothered) which would make the process "slightly" faster, but this is going to suffer as you add more columns and rows to the table, as each update is going to require a walk of the entire model.

You could put some kind of cache in, but right about then, I'd be considering fixed width columns ;)

import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

public class TableScrollTest extends JFrame {

    public TableScrollTest() {

        DefaultTableModel model = new DefaultTableModel(new Object[]{"key", "value"}, 0);
        model.addRow(new Object[]{"short", "blah"});
        model.addRow(new Object[]{"long", "blah blah blah blah blah blah blah"});

        JTable table = new JTable(model) {
            private boolean trackViewportWidth = false;
            private boolean inited = false;
            private boolean ignoreUpdates = false;

            @Override
            protected void initializeLocalVars() {
                super.initializeLocalVars();
                inited = true;
                updateColumnWidth();
            }

            @Override
            public void addNotify() {
                super.addNotify();
                updateColumnWidth();
                getParent().addComponentListener(new ComponentAdapter() {
                    @Override
                    public void componentResized(ComponentEvent e) {
                        invalidate();
                    }
                });
            }

            @Override
            public void doLayout() {
                super.doLayout();
                if (!ignoreUpdates) {
                    updateColumnWidth();
                }
                ignoreUpdates = false;
            }

            protected void updateColumnWidth() {
                if (getParent() != null) {
                    int width = 0;
                    for (int col = 0; col < getColumnCount(); col++) {
                        int colWidth = 0;
                        for (int row = 0; row < getRowCount(); row++) {
                            int prefWidth = getCellRenderer(row, col).
                                    getTableCellRendererComponent(this, getValueAt(row, col), false, false, row, col).
                                    getPreferredSize().width;
                            colWidth = Math.max(colWidth, prefWidth + getIntercellSpacing().width);
                        }

                        TableColumn tc = getColumnModel().getColumn(convertColumnIndexToModel(col));
                        tc.setPreferredWidth(colWidth);
                        width += colWidth;
                    }

                    Container parent = getParent();
                    if (parent instanceof JViewport) {
                        parent = parent.getParent();
                    }

                    trackViewportWidth = width < parent.getWidth();
                }
            }

            @Override
            public void tableChanged(TableModelEvent e) {
                super.tableChanged(e);
                if (inited) {
                    updateColumnWidth();
                }
            }

            public boolean getScrollableTracksViewportWidth() {
                return trackViewportWidth;
            }

            @Override
            protected TableColumnModel createDefaultColumnModel() {
                TableColumnModel model = super.createDefaultColumnModel();
                model.addColumnModelListener(new TableColumnModelListener() {
                    @Override
                    public void columnAdded(TableColumnModelEvent e) {
                    }

                    @Override
                    public void columnRemoved(TableColumnModelEvent e) {
                    }

                    @Override
                    public void columnMoved(TableColumnModelEvent e) {
                        if (!ignoreUpdates) {
                            ignoreUpdates = true;
                            updateColumnWidth();
                        }
                    }

                    @Override
                    public void columnMarginChanged(ChangeEvent e) {
                        if (!ignoreUpdates) {
                            ignoreUpdates = true;
                            updateColumnWidth();
                        }
                    }

                    @Override
                    public void columnSelectionChanged(ListSelectionEvent e) {
                    }
                });
                return model;
            }
        };
        table.getColumn("key").setPreferredWidth(60);
//        table.getColumn("key").setMinWidth(60);
//        table.getColumn("key").setMaxWidth(60);
//        table.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);

        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                TableScrollTest frame = new TableScrollTest();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setSize(200, 200);
                frame.setResizable(true);
                frame.setVisible(true);
            }
        });
    }
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Thanks! That is very similar to what I came up with above, but I only came up with mine because of your comments and @kleopatra's post I linked to. However, there is a small bug in your solution... your width accumulates the width value of each row... so the more rows you add, the more "dead" space you get at the end of each row. I think you want to use a max function like I did. But then I still have to add the 1-5 pixel fudge factor that I commented about in my answer. Upvoting you for your help. :-) – The111 Feb 22 '13 at 01:40
  • Also going to accept this answer because the overrides to `addNotify`, `tableChanged`, etc are smart and make it all automatic. I was planning on manually calling some `update` method every time my table changed, but having it included in the table definition like you've done is much better. – The111 Feb 22 '13 at 01:42
  • 1
    @The111 Fixed bug - also added in the intercellSpacing factor. Nice spot! – MadProgrammer Feb 22 '13 at 01:58
4

It seems then that my goal is to force the cell renderer to automatically make cells fit long strings

This isn't the job of the renderer. You must manually set the width of the columns.

See Table Column Adjuster for one way to do this.

camickr
  • 321,443
  • 19
  • 166
  • 288
1

I won't necessarily accept this answer if something smarter is posted, but here is a solution I figured out on my own based on comments posted so far and THIS post. The only catch is that the width that I was coming up with was always ~1 pixel too short (in some look-and-feel's it was ok), so I added the line near the end width += 5 which seems to make it work ok, but it feels hacky to me. Would welcome any comments on this approach.

import java.awt.Component;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

@SuppressWarnings("serial")
public class TableScrollTest extends JFrame {
    public TableScrollTest() {
        DefaultTableModel model = new DefaultTableModel(new Object[]{"key", "value"},0);
        model.addRow(new Object[]{"short", "blah"});
        model.addRow(new Object[]{"long", "blah blah blah blah blah blah blah"});

        JTable table = new JTable(model);        
        table.getColumn("key").setPreferredWidth(60);
        table.getColumn("key").setMinWidth(60);
        table.getColumn("key").setMaxWidth(60);
        table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );

        int width = 0;
        for (int row = 0; row < table.getRowCount(); row++) {
            TableCellRenderer renderer = table.getCellRenderer(row, 1);
            Component comp = table.prepareRenderer(renderer, row, 1);
            width = Math.max (comp.getPreferredSize().width, width);
        }
        width += 5;
        table.getColumn("value").setPreferredWidth(width);
        table.getColumn("value").setMinWidth(width);
        table.getColumn("value").setMaxWidth(width);

        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );
    }

    public static void main(String[] args) {
        TableScrollTest frame = new TableScrollTest();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setSize(200, 200);
        frame.setResizable(false);
        frame.setVisible(true);
    }
}
Community
  • 1
  • 1
The111
  • 5,757
  • 4
  • 39
  • 55
  • 2
    Use [`JTable.getIntercellSpacing().width`](http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html#getIntercellSpacing%28%29) instead of "fudging" the pixel padding – MadProgrammer Feb 22 '13 at 01:59
  • @MadProgrammer Cool, thanks for that tip and for the update to your solution. – The111 Feb 22 '13 at 02:41