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

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

问题描述

我在 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);

注意:

上述设置插入符号更新策略的建议不起作用.

Note:

The above suggestion to set the caret update policy does not work.

相反,您可能想要查看 智能滚动用户能够确定何时应该自动滚动.

Instead you may want to check out Smart Scrolling which gives the user the ability to determine when scrolling should be automatic or not.

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

A more detailed description of automatic scrolling in a text area can be found here: Text Area Scrolling

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

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