JTextArea+JScrollPane 中滚动+插入符行为的自定义
我在上述组件中实现我想要的行为时遇到问题。我想要的行为是:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是一个完整的答案,但评论区太有限了;-)
我的猜测是,如果你真的想挂钩滚动条行为,那么你必须玩得很肮脏并拦截用户界面安装的 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