JTable自动滚动到底部
我有一个包含 3 个 JScrollPanes(每个包含一个 Jtable)并添加了 boxlayout 的 JPanel,所以我在页面中看到 3 个表,并且动态加载数据,代码逻辑对于 3 个表几乎相同,只有列名称和一些单元格渲染不同的是,对于每个表,当新行添加到表中时,我希望自动滚动到表底部,前两个表工作完美,滚动条转到表底部,但是最后一个表的滚动条做了奇怪的事情!我对 3 个表使用完全相同的滚动方法,但前 2 个表有效,但不起作用!
有什么想法吗?
为了清晰起见,我删除了一些添加代码的列,但这就是想法;
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;
}
这是自动滚动的方法;
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
据我所知,你不需要为父母工作。只需使用这个:
我之前确实遇到过滚动问题,通过使用 SwingUtilities.invokeLater() 进行了排序,因此您可能也想尝试一下:
As far as I know, you don't need to work on the parent. Just use this:
I did have an issue with scrolling previously that was sorted by using SwingUtilities.invokeLater(), so you might want to try that as well:
我看不到您在谈论的内容,这只是 (这里也有三个JTable,但又是另一个故事了)
>例如
I can't see something that you talking about, that's just full copy of Example from http://www.exampledepot.com/egs/javax.swing.table/pkg.html
for example (here are three JTables too, but another story)
我刚刚删除了“scrollPane.setSize(1300, 400)”并且它起作用了
I just removed the "scrollPane.setSize(1300, 400)" and it worked