如何在Java GUI中设置JTextArea的AUTO-SCROLLING? [英] How to set AUTO-SCROLLING of JTextArea in Java GUI?

查看:257
本文介绍了如何在Java GUI中设置JTextArea的AUTO-SCROLLING?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在JScrollPane上嵌入了一个JTextArea并且正在使用该JTextArea进行输出。

I have embedded a JTextArea on a JScrollPane and am using that JTextArea for output.

每当输出超出JTextArea的大小时,我希望这样,JTextArea自动滚动,以便用户不必手动向下滚动查看最近的输出。

I want that whenever the ouput goes beyond the size of the JTextArea, the JTextArea scrolls automatically so that user don't have to do manual scroll down to see the recent output.

我该怎么做?

我已经将JTextArea和JScrollPane的autoscroll属性设置为true。

I have already set the autoscroll property of both JTextArea and JScrollPane to true.

推荐答案

使用JDK1时。 4.2(或更早)您在论坛中找到的最常见的建议是使用如下代码:

When using JDK1.4.2 (or earlier) the most common suggestion you will find in the forums is to use code like the following:

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

但是,我刚刚注意到在JDK5中,这个问题实际上已经通过API更改解决了。您现在可以通过在文本区域的DefaultCaret上设置属性来控制此行为。使用这种方法的代码是:

However, I have just noticed that in JDK5 this issue has actually been resolved by an API change. You can now control this behaviour by setting a property on the DefaultCaret of the text area. Using this approach the code would be:

JTextArea textArea = new JTextArea();
DefaultCaret caret = (DefaultCaret)textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

可在此处找到有关此主题的更详细说明:文本区域滚动

A more detailed description of this topic can be found here: Text Area Scrolling

这篇关于如何在Java GUI中设置JTextArea的AUTO-SCROLLING?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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