简体   繁体   English

在JScrollPane中使用JTextArea设置插入位置

[英]Set Caret position with JTextArea in JScrollPane

Right now I have a JTextArea inside of a JScrollPane. 现在,我在JScrollPane中有一个JTextArea。 For the current content it has both a vertical and horizontal scroll bar showing up. 对于当前内容,它同时显示垂直和水平滚动条。 I'm trying to implement a search functionality where a user can search for a certain string and it will set the caret position to the first occurrence of that string. 我正在尝试实现一种搜索功能,用户可以在其中搜索某个字符串,并将插入标记的位置设置为该字符串的首次出现。 However it seems that JScrollPane only scrolls vertically when I set my caret position. 但是似乎JScrollPane仅在设置插入符号位置时才垂直滚动。 So matching strings going off the JTextArea horizontally will completely get missed and the horizontal scroll bar won't scroll at all. 因此,水平离开JTextArea的匹配字符串将完全丢失,并且水平滚动条根本不会滚动。

I'm using the basic function setCaretPosition() for the JTextArea 我正在为JTextArea使用基本函数setCaretPosition()

Does anybody have any idea why my JScrollPane isn't moving horizontally using setCaretPosition() 有人知道为什么我的JScrollPane无法使用setCaretPosition()水平移动吗?

Edit: 编辑:

It appears the horizontal scroll bar is scrolling but it moves so little that it's barely noticeable. 似乎水平滚动条正在滚动,但移动得很少,几乎看不到。 I can only see the very first pixel of the character. 我只能看到角色的第一个像素。 Is there a way to have the scrollbar center (or as much as possible) to the caret position? 有没有一种方法可以使滚动条中心(或尽可能多地)位于插入符号的位置?

You should be able to use the Visible Caret Listener . 您应该能够使用Visible Caret Listener

Or you can also look at Center Line in Scroll Pane . 或者,您也可以在“滚动窗格”中查看“中心线” It only centers the line vertically, but you could customize the code to do horizontal as well. 它仅使线垂直居中,但您也可以自定义代码以使其水平放置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM