javaswingjtablepreferredsize

Expanding JTable Inside JFrame


I have the following layout that looks like this:

enter image description here

But I would like the table at the top to be minimized to just the headers, then grow vertically as clients are added. How do I go about doing this? Here is the code currently......

JFrame frame;
JTable clientTable;
DefaultTableModel clientTableModel;
JTextArea messageArea;

...

String[] tableColumnNames = ...
Object[][] data = ...

Toolkit toolkit =  Toolkit.getDefaultToolkit ();
Dimension dim = toolkit.getScreenSize();

frame = new JFrame("Server");

clientTableModel = new DefaultTableModel(0, 0);
clientTableModel.setColumnIdentifiers(tableColumnNames);

clientTable = new JTable(data, tableColumnNames);
clientTable.setPreferredScrollableViewportSize(new Dimension(dim.width-30, 82));
clientTable.setFillsViewportHeight(true);
clientTable.setModel(clientTableModel);

messageArea = new JTextArea(8, 40);
messageArea.setEditable(false);
DefaultCaret caret = (DefaultCaret) messageArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);      

frame.getContentPane().add(new JScrollPane(clientTable), "North");
frame.getContentPane().add(new JScrollPane(messageArea), "Center");
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); 

Solution

  • Each time you invoke pack(), the enclosing Window will be "sized to fit the preferred size and layouts of its subcomponents." Override getPreferredScrollableViewportSize() and return a suitable multiple of the row height. In the fragment below, N is the number of rows after which you want the scrollbar to appear.

    JTable table = new JTable(tableModel) {
    
        @Override
        public Dimension getPreferredScrollableViewportSize() {
            int h = Math.min(N, table.getRowCount());
            return new Dimension(dim.width - 30, table.getRowHeight() * h);
        }
    };
    

    When you add a new row, invoke pack(), and the enclosing Window will adopt the new size. This related example illustrates the effect for a JList.