JTable自动滚动到底部

Spr*_*ing 1 java swing scroll jtable

我有一个JPanel包含3个JScrollPanes(每个包含一个Jtable)添加了一个boxlayout,所以我在一个页面中看到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;

}
Run Code Online (Sandbox Code Playgroud)

这是自动滚动的方法;

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);
}
Run Code Online (Sandbox Code Playgroud)

Ria*_*ius 6

据我所知,你不需要在父母身上工作.只要用这个:

public void scrollToVisible(JTable table, int rowIndex, int vColIndex) {
    table.scrollRectToVisible(table.getCellRect(rowIndex, vColIndex, true));
}
Run Code Online (Sandbox Code Playgroud)

我确实有一个先前使用SwingUtilities.invokeLater()排序的滚动问题,所以你可能也想尝试一下:

public void scrollToVisible(final JTable table, final int rowIndex, final int vColIndex) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            table.scrollRectToVisible(table.getCellRect(rowIndex, vColIndex, false));
        }
    });
}
Run Code Online (Sandbox Code Playgroud)