我没有足够的声誉来发表评论,但想为以后的读者提供一些见解,以了解为何setText似乎不会触发侦听器,而appendText却会触发,就像Math的回答一样。
我自己遇到类似问题时就找到了这个答案,并调查了代码。目前,这是Google搜索中“ javafx textarea settext
scroll”的最高搜索结果。
setText确实会触发侦听器。根据TextInputControl(textarea的超类)的doSet方法的javadoc:
* doSet is called whenever the setText() method was called directly * on the TextInputControl, or when the text property was bound, * unbound, or reacted to a binding invalidation. It is *not* called * when modifications to the content happened indirectly, such as * through the replaceText / replaceSelection methods.
在doSet方法内部,对updateText()进行了调用,textarea覆盖了该方法:
@Override final void textUpdated() { setScrollTop(0); setScrollLeft(0); }因此,当您像Math的答案一样在侦听器中设置滚动量时,会发生以下情况:
- TextProperty已更新
- 将调用您的听众,并设置了滚动条
- doSet被称为
- textUpdated被称为
- 滚动设置回到左上方
当您附加“”时,
- TextProperty已更新
- 将调用您的听众,并设置了滚动条
上面的javadoc很清楚为什么是这种情况-
仅在使用setText时才调用doSet。实际上,appendText调用insertText,后者调用replaceText-
并且javadoc进一步声明replaceText不会触发对doSet的调用。
这种行为非常令人讨厌,特别是因为这些都是最终方法,乍一看并不明显-但这不是错误。



