简体   繁体   English

正确滚动到JTable的选定行

[英]Scroll to selected row correctly for JTable

I'm using a JTable to display data. 我正在使用JTable来显示数据。 When a row is selected programmatically, it should (automatically) scroll that row into view so that it is the first row on top. 以编程方式选择一行时,应(自动)将该行滚动到视图中,使其成为顶部的第一行。 For this I have the following method: 为此,我有以下方法:

private static void scrollToSelectedRow(JTable table)
{
    JViewport viewport = (JViewport) table.getParent();
    Rectangle cellRectangle = table.getCellRect(table.getSelectedRow(), 0, true);
    Rectangle visibleRectangle = viewport.getVisibleRect();
    table.scrollRectToVisible(new Rectangle(cellRectangle.x, cellRectangle.y, (int) visibleRectangle.getWidth(), (int) visibleRectangle.getHeight()));
}

The problem is that calling this may or may not scroll correctly, eg the selected row may be on top or not in a non-deterministic way. 问题是调用此方法可能会正确滚动,也可能无法正确滚动,例如,所选行可能以不确定的方式位于顶部或不在顶部。 In order to fix this, I tried calling the method twice with a delay in-between as well as repainting it: 为了解决这个问题,我尝试两次调用该方法,中间有一个延迟,然后重新绘制它:

public static void setSelectedRow(JTable table, int rowIndex, int columnIndex)
{
    table.setRowSelectionInterval(rowIndex, columnIndex);
    scrollToSelectedRow(table);
    try
    {
        Thread.sleep(100);
    } catch (InterruptedException exception)
    {
        exception.printStackTrace();
    }
    scrollToSelectedRow(table);
    table.repaint();
}

This works a lot better but still sometimes glitches the table columns out since apparently it is not smart to halt the EDT while it is updating. 这种方法效果更好,但有时仍会使表列出现故障,因为显然在更新时暂停EDT并不明智。 The repaint() call appears to prevent the rows from "overlapping" in a similar fashion. 出现repaint()调用是为了防止行以类似的方式“重叠”。 The graphical glitches can be fixed easily by moving the mouse over the affected rows/columns though but it should not happen. 尽管可以通过将鼠标移到受影响的行/列上来轻松解决图形故障,但是这种情况不会发生。

How can I gracefully perform the scrolling without waiting and without having graphical glitches? 如何在不等待且没有图形故障的情况下优雅地执行滚动?

Code looks reasonable. 代码看起来合理。 Normally the trick is to make sure the Rectangle width/height is the size of the viewport to force the scroll. 通常,技巧是确保Rectangle的宽度/高度是强制滚动的视口的大小。

Two thoughts. 两个想法。

  1. Get rid of the Thread.sleep(). 摆脱Thread.sleep()。 all that will do is prevent the GUI from repainting itself for 100ms. 所有要做的就是防止GUI自行重绘100ms。

  2. Try wrapping the scrollRectToVisible(...) in a SwingUtlities.invokeLater(...) . 尝试将scrollRectToVisible(...)包装在SwingUtlities.invokeLater(...)

If point 2 doesn't help then post a proper [mcve] that demonstrates the problem. 如果第2点没有帮助,则发布适当的[mcve]来演示问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM