将 JScrollPane 滚动到底部

2022-08-31 19:59:59

我需要将JScrollPane滚动到底部。JScrollPane包含一个JPanel,其中包含许多JLabel。

要滚动到顶部,我只做:

scrollPane.getViewport().setViewPosition(new Point(0,0));

但是我如何准确地滚动到最底部?(太远,它抖动)


答案 1
JScrollBar vertical = scrollPane.getVerticalScrollBar();
vertical.setValue( vertical.getMaximum() );

答案 2

经过几个小时的尝试使用scrollRectToVisible()方法找到答案以外的答案,我成功了。我发现,如果在将文本输出到滚动窗格中的文本区域后使用以下代码,它将自动聚焦在文本区域的底部。

textArea.setCaretPosition(textArea.getDocument().getLength());

所以,至少对我来说,我的打印方法看起来像这样

public void printMessage(String message)
{
    textArea.append(message + endL);
    textArea.setCaretPosition(textArea.getDocument().getLength());
}

推荐