仅当附加文本时,JTextArea才会滚动到底部 [英] JTextArea scroll to bottom only if text is appended

查看:95
本文介绍了仅当附加文本时,JTextArea才会滚动到底部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个 JTextArea ,每次将文本追加到该文本区域时,它都会滚动到底部。否则,用户应该能够滚动顶部并查看上一条消息。我使用了这段代码:

I am trying to create a JTextArea which scrolls to bottom every time a text is appended to that text area. Otherwise, the user should be able to scroll top and see previous message. I used this code:

JTextArea terminalText  = new JTextArea();
JPanel terminal = new JPanel();
terminal.setLayout(new BorderLayout()); 
add(terminal);  //Adds the terminal to mother JPanel

//I added scrollbar to my JTextArea
JScrollPane scroll = new JScrollPane(terminalText);  
terminal.add(scroll, BorderLayout.CENTER);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

scroll.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {  
public void adjustmentValueChanged(AdjustmentEvent e) {  
 e.getAdjustable().setValue(e.getAdjustable().getMaximum());  
}});

到目前为止,这段代码似乎使我的文本区域滚动到的底部每次我使用 terminalText.append terminalText 附加内容时,将显示terminalText 文本区域。

So far this code seems to make my text area scroll to bottom of the terminalText text area every time I append something to terminalText using terminalText.append.

但是,用户无法使用滚动条滚动到顶部以查看上一条消息。有没有办法来解决这个问题?我应该使用 DocumentListener 来实现这个目标吗?

However, the user cannot use scroll bar to scroll to the top to see previous message. Is there a way to fix this? Should I be using DocumentListener to achieve this?

推荐答案

签出< a href =https://tips4java.wordpress.com/2013/03/03/smart-scrolling/\"rel =nofollow>智能滚动。

如果滚动条位于底部,则随附文本,您将看到新文本。

If the scrollbar is at the bottom, then as text is appended you will see the new text.

如果用户滚动到其他位置,则视口将保持不变,直到用户滚动到底部。

If the user has scrolled to a different position, then the viewport will stay there until the user scrolls back to the bottom.

这篇关于仅当附加文本时,JTextArea才会滚动到底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆