为JTable

时间:2016-12-26 15:17:27

标签: java swing jtable

我使用JTable来显示数据。当以编程方式选择行时,它应该(自动)将该行滚动到视图中,以便它是顶部的第一行。为此,我有以下方法:

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()));
}

问题是调用它可能会也可能不会正确滚动,例如所选行可以以非确定性方式在顶部或不在顶部。为了解决这个问题,我尝试了两次延迟调用方法并重新绘制它:

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();
}

这样做效果要好得多,但有时仍然会将表格列出来,因为显然在更新时暂停EDT是不明智的。 repaint()调用似乎可以阻止行重叠"以类似的方式。通过将鼠标移动到受影响的行/列上可以轻松修复图形毛刺,但不应该发生。

如何在不等待和没有图形故障的情况下优雅地执行滚动操作?

1 个答案:

答案 0 :(得分:3)

代码看起来很合理。通常的技巧是确保Rectangle width / height是视口的大小以强制滚动。

两个想法。

  1. 摆脱Thread.sleep()。所做的就是阻止GUI重新绘制100ms。

  2. 尝试将@IBAction func addToMap(_ sender: Any) { let lat = Double(latitudeField.text!) let long = Double(longitudeField.text!) self.coordinates.append(CLLocationCoordinate2D(latitude: lat!, longitude: long!)) //here we pass the coordinate array to mapViewController if let mapViewController = self.tabBarController?.viewControllers?[1] as? MapViewController { mapViewController.coordinates = self.coordinates } } 包裹在scrollRectToVisible(...)

  3. 如果第2点没有帮助,则发布一个证明问题的正确[mcve]。

相关问题