JTable滚动到指定的行索引

Chr*_*ail 45 java swing jtable jscrollpane

JScrollPane.根据我的应用程序中发生的事件,我在运行时将一个位于行内的JTable 添加到表中.我想让一个新的行添加到表格时,scoll窗格滚动到表格的底部.

对于JLists有[ensureIndexIsVisible][1]()强制列表中的特定索引可见.我正在寻找相同的东西,但对于JTable.看起来我可能不得不手动移动滚动窗格上的滚动视图,但我认为必须有一个更简单的方法.

小智 70

这很简单,JTable也有scrollRectToVisible方法.如果你愿意,你可以尝试这样的东西,如果添加了一条新记录,滚动窗格会转到底部:

jTable1.getSelectionModel().setSelectionInterval(i, i);
jTable1.scrollRectToVisible(new Rectangle(jTable1.getCellRect(i, 0, true)));
Run Code Online (Sandbox Code Playgroud)

是最后添加的记录.

  • ......以及新的Rectangle()应该是什么意思?getCellRect()已经返回一个Rectangle! (3认同)

Pie*_*rre 35

请参阅此示例:http://www.exampledepot.com/egs/javax.swing.table/Vis.html

更新:链接现已过时,这是代码(来自http://smi-protege.stanford.edu/repos/protege/protege-core/trunk/src/edu/stanford/smi/protege/util/ComponentUtilities. java)

public static 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);

        table.scrollRectToVisible(rect);

        // Scroll the area into view
        //viewport.scrollRectToVisible(rect);
    }
Run Code Online (Sandbox Code Playgroud)

  • table.scrollRectToVisible(table.getCellRect(row,column,true)); (5认同)
  • 错了,太复杂了!这可以在一行中完成: (2认同)

Val*_*her 5

JList内部使用scrollRectToVisible并指定要滚动到的坐标.我认为你将不得不为JTable重新编写类似的功能.