---
title: "JScrollPane实现自动滚动到底部 "
author: "conkeyn"
date: "2014-06-05T14:02:13Z"
tags: []
categories: ["编程语言"]
slug: "jscrollpane"
draft: false
lastmod: "2014-06-05T14:05:36Z"
id: 2076218
url: "https://conkeyn.iteye.com/blog/2076218"
---

转自：[http://blog.csdn.net/dancen/article/details/7379847](http://blog.csdn.net/dancen/article/details/7379847)

 

1\. JTable( 放在JScrollPane中 )中加入一行后, 然后让其获得焦点且滚动条自动下来!

 

```
int rowCount = table.getRowCount();
table.getSelectionModel().setSelectionInterval(rowCount-1, rowCount-1);
Rectangle rect = table.getCellRect(rowCount-1, 0, true);
//table.repaint(); 若需要的话
//table.updateUI();若需要的话
table.scrollRectToVisible(rect);
```

 

注：table.scrollRectToVisible(rect)必须在table.repaint()和 table.updateUI()（如果有的话）之后，不然有时滚动条不能滚动到最底下，亲身体验过。

 

2\. 直接操纵JScrollPane中的JScrollBar

```
JScrollPane sPane = new JScrollPane(table);
JScrollBar sBar = sPane.getVerticalScrollBar(); //得到了该JScrollBar
```

具体操作：

```
sBar.setValue(int value); //设置一个具体位置，value为具体的位置
int value = sBar.getValue();//得到JScrollBar现在的位置
sBar.getMaximum(); //得到允许的最大值
sBar.getMinimum(); //得到允许的最小值
```

3\. JTextArea+JScrollPane滚动条自动在最下边  
(1) 在JTextArea插入最后一条消息之后，使用selectAll()将光标强制移动到JTextArea的最后，实现滚动条的自动滚动。（Aviva中采用的方式）

 

(2) 在JTextArea插入最后一条消息之后，使用以下代码将光标移到最后，实现滚动条的自动滚动。

```
recvArea.setCaretPosition(recvArea.getText().length());
```

(3) 在JTextArea加载了自动滚动条JScroll之后，将JTextArea加入到JScrolPanel的ViewPort中: （有一些Bug，使得图像有点闪烁）

```
recvScrollPane.getViewport().add(recvArea, null);
```

     然后在JTextArea插入最后一条新消息之后，将滚动条的Viewport重新设置到最底端的位置：

```
int height = 20;
Point p = new Point();
p.setLocation(0, recvArea.getLineCount() * height);
recvScrollPane.getViewport().setViewPosition(p);
```

4\. 设置jScrollPane中的JTextArea自动到底部

```
int height=10;
Point p = new Point();
p.setLocation(0,this.jTextArea1.getLineCount()*height);
this.jScrollPane1.getViewport().setViewPosition(p);
```

利用JTextArea载入文本后，若希望JTextArea显示时直接将滚动条滚动直最下方，目前发现仅第4种方法有效：即设置JScrollPane的视口JViewport显示坐标。