I have a BoxLayout (in a panel of a BorderLayout) in which I've put a JTable and a button vertically. I would like the table to have a fixed width and that the height should resize itself up to filling the panel. At the moment, I'm fine with the displayed width but not that it's filling up the whole panel height. For example, if there are zero data in the table, I would like only the column names to be shown. I've tried things like setViewportView() and setPreferredSize(), but can't really make it work. Any suggestions? Is it in the layout or scrollpane?
String[] columnNames = { "Date", "Type"
};
Object[][] data = {
};
JTable myTable = new JTable(data, columnNames);
JButton okButton = new JButton("OK");
JPanel panWest = new JPanel();
panWest.setLayout(new BoxLayout(panWest, BoxLayout.PAGE_AXIS));
JScrollPane scrollPane = new JScrollPane(myTable);
panWest.add(scrollPane);
panWest.add(okButton);
EDIT This is what ended up working:
Dimension dimension = new Dimension();
dimension.height = (myTable.getRowCount()*myTable.getRowHeight())+
myTable.getTableHeader().getPreferredSize().height;
dimension.width = myTable.getColumnModel().getTotalColumnWidth();
scrollPane.setMaximumSize(dimension);