[SOLVED] JTable in JScrollPane renders partly invisible
I have a JTable added to a JScrollPane with the auto resize mode of the table set to AUTO_RESIZE_OFF. This allows me to specify the widths of the columns to always be larger than the widest rendered component in a column. i.e. I want all data in a cell always visible. It also enables the table to be larger than the JScrollPane viewport size and the JScrollPane will display scroll bars as necessary.
PrintJobTable table = new PrintJobTable(model); //class extends JTable
JscrollPane scrollPane = new JScrollPane(table);
table.initColumnSizes(); //sets column widths appropriately so all data is seen
This all works fine when application is launched. However, after a user
enters data into a cell, I resize the column width appropriatly so all data can be seen using the following setColumnWidth(int col) method.
The method sets the column width of the specified column to be larger than (with a margin either side) the widest object in the column including all cells and header.
This method is called after data is changed in the column. The width of the column is updated fine. However if the the width of the column has increased from what it was originally, the overall table size has also increased and the region of the table at the right hand most side which exceeds the original table size appears invisible. I am not sure if this is a problem with the JTable or JScrollPane rendering and what methods I can call to fix the problem. After setting the column I have tried things like....
but none of them do anything, and I am blundering in the dark.
public void setColumnWidth(int col)
//The margin to place either side of the component in a cell
int margin = 20;
//Get the column and make it non resiable by the user
TableColumn column = getColumnModel().getColumn(col);
//Set the width to be the header width of this column
TableCellRenderer headerRenderer = getTableHeader().getDefaultRenderer();
Component comp = headerRenderer.getTableCellRendererComponent(
false, false, 0, 0);
int width = comp.getPreferredSize().width;
//Set the width to be the larger of the header or a cell width in this column
for (int i=0; i<this.getRowCount(); i++)
TableCellRenderer renderer = this.getCellRenderer(i, col);
Component c = renderer.getTableCellRendererComponent(this, getValueAt(i, col), false, false, i, col);
width = Math.max(width, c.getPreferredSize().width);
//Usethe width of the largest component (header or cell) plus a margin on other side.
column.setPreferredWidth(width + 2 * margin);
column.setMinWidth(width + 2 * margin);
column.setMaxWidth(width + 2 * margin);