文本区域无法使用插入符号正确滚动

Text area can't scroll properly with caret

我将 JTextArea 用于我的简单聊天程序的聊天,我添加了一个插入符号,以便在附加文本时它会自动滚动。这引发了用户在大量使用聊天时无法滚动的问题。

我已经尝试查看插入符的选项,并查看了滚动窗格选项,但是当用户滚动时没有不向下滚动的内容。

我打算允许用户滚动但不会因为有人发送了消息而立即向下滚动。理想的是它像 Discord 一样工作,只有当用户一直向下滚动或类似的东西时它才会向下滚动。

What would be ideal is it it worked like Discord, where it only scrolls down when the user scrolls all the way down or something like that.

查看 Smart Scrolling。它在滚动条上添加了一个 AdjustmentListener 来控制滚动:

  1. 滚动条在底部时会自动继续滚动。

  2. 不在底部时不会滚动。用户需要滚动到底部才能重新激活自动滚动。

我的推荐和Camickr的相似。根据用户是否滚动到底部,向滚动条和 enable/disable 插入符移动添加一个更改监听器。如果滚动条处于最大值,则启用插入符号移动。如果不是,则将其禁用。

YourJScrollPane.getVerticalScrollBar().getModel().addChangeListener()
{
   //Override stateChanged(ChangeEvent e) With Caret Movement Switch
}

通过调用模型(这是一个 BoundedRangeModel)的范围、值和最大范围来检测和比较当前滚动条位置。

https://docs.oracle.com/javase/7/docs/api/javax/swing/BoundedRangeModel.html

/*Where to find the needed scrollbar position values*/
YourJScrollPane.getVerticalScrollBar().getModel().getExtent()
YourJScrollPane.getVerticalScrollBar().getModel().getValue()
YourJScrollPane.getVerticalScrollBar().getModel().getMaximum() //Bottom Position

/*Pseudocode*/
if (Value + Extent == Maximum)
{
    /*Enable Caret Movement - User is at bottom of page*/ 
}
else
{
    /*Disable Caret Movement - User is not at bottom of page*/
}

如有任何改进或建议,请在下方发表评论。