I have a JPanel containing 3 JScrollPanes(each contains a Jtable) added with a boxlayout, so I see 3 tables in a page and I load data dynamically, the code logic is almost same for 3 tables and only the column names and some cell rendering is different, For each tables I wanted to have auto scrolling to bottom of the table when new rows added to table, first 2 tables work perfect and scrollbar goes to bottom of table, but this last table’s scroll bar do weird things! I use exactly the same scrolling method for 3 tables but first 2 works this does not work!
Any ideas?
I removed some column adding code for clearity but this is the idea;
private JScrollPane fillThirdTable(ArrayList<DisplayVariable> displayList) {
DefaultTableModel model = new DefaultTableModel();
ToolTipTable answer = new ToolTipTable(model);
answer.setRowHeight(60);
answer.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
answer.setSize(1300, 400);
DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();
dtcr.setHorizontalAlignment(SwingConstants.CENTER);
answer.getColumn("Display Variable ID").setCellRenderer(dtcr);
JScrollPane scrollPane = null;
for (DisplayVariable var : displayList) {
model.addRow(new Object[] { id, shown, name, value });
answer.setFillsViewportHeight(true);
}
TableColumn c= answer.getColumnModel().getColumn(3);
c.setCellRenderer(new MultiLineCellRenderer());
TableColumn c2= answer.getColumnModel().getColumn(2);
c2.setCellRenderer(new MultiLineCellRenderer());
scrollPane = new JScrollPane(answer);
scrollPane.setSize(1300, 400);
//here I call the method
scrollToVisible(answer, (displayList.size()-1), 1);
return scrollPane;
}
and this is the method for autoscrolling;
public void scrollToVisible(JTable table, int rowIndex, int vColIndex) {
if (!(table.getParent() instanceof JViewport)) {
return;
}
JViewport viewport = (JViewport)table.getParent();
// This rectangle is relative to the table where the
// northwest corner of cell (0,0) is always (0,0).
Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
// The location of the viewport relative to the table
Point pt = viewport.getViewPosition();
// Translate the cell location so that it is relative
// to the view, assuming the northwest corner of the
// view is (0,0)
rect.setLocation(rect.x-pt.x, rect.y-pt.y);
// Scroll the area into view
viewport.scrollRectToVisible(rect);
}
I just removed the “scrollPane.setSize(1300, 400)” and it worked