我有一个 JTextArea。我有一个函数,可以在调用某些组合时选择一定数量的文本。做得很好。问题是,当选择某些文本并按下 VK_LEFT 时,我想将插入符号移动到选择开始。 KeyListener实现正确,我用其他方式测试了它。问题是,当我编写以下代码时:
@Override public void keyPressed( KeyEvent e) {
if(e.getKeyChar()==KeyEvent.VK_LEFT)
if(mainarea.getSelectedText()!=null)
mainarea.setCaretPosition(mainarea.getSelectionStart());
}
并将此侦听器的实例添加到 mainarea,选择一些文本(使用我的功能)并按左箭头键,插入符号位置设置为选择的末尾...并且我不会将其放在开头...什么到底是怎么回事? :S
这是一个代码片段
Action moveToSelectionStart = new AbstractAction("moveCaret") {
@Override
public void actionPerformed(ActionEvent e) {
int selectionStart = textComponent.getSelectionStart();
int selectionEnd = textComponent.getSelectionEnd();
if (selectionStart != selectionEnd) {
textComponent.setCaretPosition(selectionEnd);
textComponent.moveCaretPosition(selectionStart);
}
}
public boolean isEnabled() {
return textComponent.getSelectedText() != null;
}
};
Object actionMapKey = "caret-to-start";
textComponent.getInputMap().put(KeyStroke.getKeyStroke("LEFT"), actionMapKey);
textComponent.getActionMap().put(actionMapKey, moveToSelectionStart);
注意:不建议重新定义通常安装的键绑定,例如 f.i.任何箭头键,用户可能会感到非常恼火;-) 最好寻找一些尚未绑定的键。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)