I've run into a similar situation where we have nested Hierarchical tables and that sometimes the child table is wider then the parent and other times the child is not as wide.
So we extended JScrollPane and added in the logic for getPreferredSize from FitScrollPane
Here is where we plug our TableScrollPane into getTableComponentFactory for the parent
- Code: Select all
private HierarchicalTableComponentFactory getTableComponentFactory() {
return new HierarchicalTableComponentFactory() {
@Override
public Component createChildComponent(HierarchicalTable table, Object model, int rowIndex) {
ChildContainerTableModel tableModel = (ChildContainerTableModel) model;
BaseListingTable childTable = createChildContainerTable(tableModel);
childTable.setComponentFactory(getTableComponentFactory());
JScrollPane pane = new ChildTableScrollPane(childTable);
TreeLikeHierarchicalPanel treeLikeHierarchicalPanel = new TreeLikeHierarchicalPanel(pane);
treeLikeHierarchicalPanel.setBackground(childTable.getMarginBackground());
return treeLikeHierarchicalPanel;
}
};
}
I have not thoroughly tested this TableScrollPane it is a quick and dirty for us to be able to handle children that are wider than their parent for an engineering release we have - so if you see funky behavior I apologize, I jjust thought I'd post it incase it might help someone else
- Code: Select all
public class TableScrollPane extends JScrollPane {
public TableScrollPane(JTable table) {
//NOTE: Important for dynamic resizing - see method comments
ComponentListener listener = getScrollPaneComponentListener(table);
addComponentListener(listener);
//This is supposed to handle scroll bars as necessary
setViewportView(table);
}
@Override
public Dimension getPreferredSize() {
getViewport().setPreferredSize(getViewport().getView().getPreferredSize());
return super.getPreferredSize();
}
public JTable getTable() {
return (JTable) getViewport().getView();
}
private ComponentListener getScrollPaneComponentListener(final JTable table) {
return new ComponentListener() {
@Override
public void componentHidden(ComponentEvent e) {
resize();
}
@Override
public void componentMoved(ComponentEvent e) {
resize();
}
@Override
public void componentResized(ComponentEvent e) {
resize();
}
@Override
public void componentShown(ComponentEvent e) {
resize();
}
private void resize() {
Container tableContainer = table.getParent();
Double tableContainerWidth = tableContainer.getSize().getWidth();
Double tablePreferredWidth = table.getPreferredSize().getWidth();
if (tableContainer instanceof JViewport) {
if (tableContainerWidth < tablePreferredWidth) {
//TableContainer width is smaller than preferred table width - don't auto resize the columns - allow scroll bar to display
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
}
else {
//TableContainer width is bigger than table preferred width - allow the columns to grow to eat up the space
table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
}
}
}
};
}
}