当滚动窗格包装文本窗格时,如何防止JScrollPane箭头键处理移动插入符号[英] How to prevent JScrollPane arrow key handling from moving caret when Scroll Pane wraps Text Pane

问题描述

我有以下要求:

我需要一个可滚动的 JTextPane.用户可以在该文本窗格中键入,或者可以在其中插入不是用户键入的文本.想像一个 IM 窗口之类的东西.尽管窗口必须是可滚动的以允许用户查看以前键入的文本,但插入符号不应从文本末尾的位置移动.用户输入的任何文本都将始终显示在末尾.

在 JTextPane 中,当用户使用滚动条滚动时,插入符号不会移动.视口被调整.但是,当用户按下向上和向下箭头键时,JTextPane 插入符号会随之移动(无论窗口是否滚动).

我想要的是向上箭头键的功能与用鼠标向上移动滚动条的功能相同.箭头键应该与插入符号无关.

我尝试了以下方法,但没有成功:1) 为我的文本窗格类(使用 JTextPane.addKeymap() 和 Keymap.addActionForKeyStroke())向 Keymap 添加"无操作"操作.这会阻止插入符号移动,但会阻止将操作传递到滚动窗格以滚动视图.2)从我的文本窗格类的键盘映射中删除箭头键.这会影响我的应用程序中的所有 JTextPanes,这不是我想要的.

我想要的是向我的 TextPane 键盘映射添加一个操作,该操作只需调用向上和向下箭头的 ScrollPane 操作.

最好的方法是什么?

我想到的一种可能性是实现一个 KeyListener(它在键盘映射之前接收击键)来捕获这些键,然后手动实现滚动.但这似乎需要我计算字体大小等.有没有更简单的方法?

理想的情况是如果有某种方法可以将插入符号"锚定"到文本的末尾.

推荐答案

你将不得不修改 KeyBindings

试试这个开始

InputMap im = textArea.getInputMap(WHEN_FOCUSED);
ActionMap am = textArea.getActionMap();

am.get("caret-down").setEnabled(false);
am.get("caret-up").setEnabled(false);

现在你已经开始工作了,你需要担心所有这些

selection-up = shift pressed UP
caret-next-word = ctrl pressed RIGHT
selection-previous-word = shift ctrl pressed LEFT
selection-up = shift pressed KP_UP
caret-down = pressed DOWN
caret-previous-word = ctrl pressed LEFT
caret-end-line = pressed END
selection-page-up = shift pressed PAGE_UP
caret-up = pressed KP_UP
delete-next = pressed DELETE
caret-begin = ctrl pressed HOME
selection-backward = shift pressed LEFT
caret-end = ctrl pressed END
delete-previous = pressed BACK_SPACE
selection-next-word = shift ctrl pressed RIGHT
caret-backward = pressed LEFT
caret-backward = pressed KP_LEFT
selection-forward = shift pressed KP_RIGHT
delete-previous = ctrl pressed H
unselect = ctrl pressed BACK_SLASH
insert-break = pressed ENTER
selection-begin-line = shift pressed HOME
caret-forward = pressed RIGHT
selection-page-left = shift ctrl pressed PAGE_UP
selection-down = shift pressed DOWN
page-down = pressed PAGE_DOWN
delete-previous-word = ctrl pressed BACK_SPACE
delete-next-word = ctrl pressed DELETE
selection-backward = shift pressed KP_LEFT
selection-page-right = shift ctrl pressed PAGE_DOWN
caret-next-word = ctrl pressed KP_RIGHT
selection-end-line = shift pressed END
caret-previous-word = ctrl pressed KP_LEFT
caret-begin-line = pressed HOME
caret-down = pressed KP_DOWN
selection-forward = shift pressed RIGHT
selection-end = shift ctrl pressed END
selection-previous-word = shift ctrl pressed KP_LEFT
selection-down = shift pressed KP_DOWN
insert-tab = pressed TAB
caret-up = pressed UP
selection-begin = shift ctrl pressed HOME
selection-page-down = shift pressed PAGE_DOWN
delete-previous = shift pressed BACK_SPACE
caret-forward = pressed KP_RIGHT
selection-next-word = shift ctrl pressed KP_RIGHT
page-up = pressed PAGE_UP

本文地址:https://www.itbaoku.cn/post/978456.html