【问题标题】:Setting caret position in JTextArea在 JTextArea 中设置插入符号位置
【发布时间】:2011-08-22 12:38:11
【问题描述】:

我有一个 JTextArea。我有一个函数可以在调用某种组合时选择一定数量的文本。它做得很好。 The thing is, I want to move caret to the selection beginning when some text is selected and VK_LEFT is pressed. KeyListener 已正确实现,我以其他方式对其进行了测试。问题是,当我编写以下代码时:

@Override public void keyPressed( KeyEvent e) {
        if(e.getKeyChar()==KeyEvent.VK_LEFT)
            if(mainarea.getSelectedText()!=null)
                mainarea.setCaretPosition(mainarea.getSelectionStart());
    }

并将此侦听器的一个实例添加到 mainarea,选择一些文本(使用我的功能)并按左箭头键,插入符号位置设置为选择的末尾...我不会在开头。 .. 怎么了? :S

【问题讨论】:

  • 不要使用 KeyListeners,这是绝对不行的 ;-) 相反,使用键绑定 ..
  • IIRC,您可以在设置选择时将插入符号设置为开头。为此,您必须设置从结束位置到开始位置的选择。因此,当用户按下左键时,插入符号将位于选择的开始。这不是你想要达到的吗?

标签: java swing listener jtextarea textselection


【解决方案1】:

这是一个代码 sn-p

    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。任何箭头键,用户可能会非常恼火;-) 最好寻找一些尚未绑定的。

【讨论】:

  • +1,用于键绑定。希望有一天人们会忘记 KeyListeners。虽然我会扩展 TextAction 以与编辑器工具包中定义的 Actions 保持一致。然后您可以使用 getFocusedComponent() 来获取要操作的文本组件。
  • 我想我需要再次澄清一下自己:) 一般来说,在 Swing 组件上使用 Key Bindings 时,我会扩展 AbstractAction。但是,当向文本组件添加操作时,我会扩展 TextAction。
  • @camickr - 我就是这么理解你的 :-) 无论如何,这里的要求有点病态。
  • @camickr 和 kleopatra- 你为什么这样做而不是使用文本组件的 Keymap 和“addActionForKeyStroke”方法?每种方法的优缺点?
  • @harmanjd 这是旧的 api(已弃用?不记得了),仅适用于 textComponents。较新的样式 keyBindings 适用于所有 JSomething 并且更灵活。请注意,在内部,注册到 keyMap 的所有内容都被包装以适应 input/actionMap
猜你喜欢
  • 2011-06-05
  • 2013-07-18
  • 2013-05-21
  • 1970-01-01
  • 1970-01-01
  • 2010-10-06
  • 2013-07-25
  • 2020-08-17
  • 1970-01-01
相关资源
最近更新 更多