JTextArea+JScrollPane 中滚动+插入符行为的自定义

发布于 2024-12-01 23:17:19 字数 585 浏览 2 评论 0原文

我在上述组件中实现我想要的行为时遇到问题。我想要的行为是:
1)默认情况下,当新内容附加到 JTextArea 时,它会自动滚动到最后插入的行。我成功做到了这一点:
DefaultCaret 插入符号 = (DefaultCaret)textArea.getCaret(); caret.setUpdatePolicy(DefaultCaret.NEVER_ALWAYS);
2)当用户使用鼠标或键盘移动滚动条时,应禁用自动滚动并显示用户滚动到的文本(这里我尝试实现在操作时设置 DefaultCaret.NEVER_NEVER 的AdjustmentListener但将其设置为 NEVER 后,我实际上再也无法滚动到某个地方)
3)当用户将滚动条移动到最后插入的行时,应该重新采取第1)行中提到的默认行为

我唯一看到这样做的是根据文档长度和滚动的当前位置以某种方式计算插入符位置,但说实话我实在不喜欢这种方式。我想知道是否有其他更优雅和正确的方法可以做到这一点?

谢谢,Serhiy。

编辑:我发现了非常相似的问题并通过源代码示例回答。可以找到答案

I have a problem implementing the behavior I want in mentioned components. The behavior I want is:
1) By default, when new content is appended to JTextArea, it's auto scrolling to the last inserted line. This one I managed to do with:
DefaultCaret caret = (DefaultCaret)textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.NEVER_ALWAYS);

2) When user either with mouse or with keyboard moving scrollbar, auto scrolling should be disabled and the text to which user has scrolled is displayed (here I tried to implement AdjustmentListener which on action was setting DefaultCaret.NEVER_NEVER but after setting it to NEVER, I could actually never more scroll to somewhere)
3) When user moves scrollbar to the last inserted line, default behavior mentioned in line 1) should be retaken

The only was I see to do this is somehow calculate caret position depending on document length and the current position of scroll, but to be honest I don't really like this way. I would like to know if there is some other, more elegant and correct method doing this?

Thanks, Serhiy.

EDIT: I have found very similar question and answer to it with source code example. Answer can be found here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

未央 2024-12-08 23:17:19

这不是一个完整的答案,但评论区太有限了;-)

我的猜测是,如果你真的想挂钩滚动条行为,那么你必须玩得很肮脏并拦截用户界面安装的 MouseListener并用您自己的滚动条操作(在其 ActionMap 中)包装默认滚动条操作,并在那里实现插入符号策略的切换。

另一方面:我不确定您是否真的想要它:-) 至少假设文本始终添加在末尾,因为只有在文本之前插入时才会发生自动滚动插入符号位置。您的所有用户必须执行以下操作

  • 才能停止自动滚动:将插入符号从末尾移开
  • 或允许自动滚动:将插入符号移至末尾

This isn't a complete answer, but the comment area is just too limiting ;-)

My guess is that if you really want to hook into the scrollbar behaviour, then you'd have to play very dirty and intercept the ui-installed MouseListener and wrap the default scrollbar actions (in its ActionMap) with your own and implement the toggle of the caret policy there.

On the other hand: I'm not sure you really want it :-) At least assuming the text is always added at the end, because auto-scrolling only ever happens if the text is inserted before the caret location. All your users have to do

  • for stopping automatic scrolling: move the caret away from the end
  • tor allowing automatic scrolling: move the caret to the end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文