摇摆。 JTextPane 中的默认键绑定

Swing. Default keybindings in JTextPane

现在我正在研究 C IDE。因为它的主题是 Motif,我的问题是如何将默认 KeyStroke(Ctrl + C - 复制,Ctrl + V - 粘贴)添加到 JTextPane。在 Motif L&F 中,JTextPane 不会对这些击键做出反应。如何让它对这些键执行所需的操作。

In Motif L&F, JTextPane doesn't react on these KeyStrokes. How to make it perform the desired actions on these keys.

您需要添加自己的 Key Bindings 才能将 Action 绑定到 KeyStroke

查看 Key Bindings 程序以列出给定 LAF 的任何 Swing 组件的现有绑定。

然后显示如何与不同的 KeyStroke 共享一个 Action:

 KeyStroke existingKeyStroke = KeyStroke.getKeyStroke("ENTER");
 KeyStroke addedKeyStroke = KeyStroke.getKeyStroke("control Z");
 InputMap im = component.getInputMap(...);
 im.put(addedKeyStroke, im.get(existingKeyStroke));

或使用 KeyStroke 将绑定添加到 Action:

 KeyStroke addedKeyStroke = KeyStroke.getKeyStroke("control Z");
 InputMap im = component.getInputMap(...);
 im.put(addedKeyStroke, "caret-end-word"); 

我会让你 运行 程序来使用现有的 KeyStroke 或 "action name" 使用。

以上示例显示了如何更改单个组件的绑定。 link 还将展示如何通过访问所有文本窗格共享的 InputMap 来完成所有 JTextPanes。

InputMap im = (InputMap)UIManager.get("TextField.focusInputMap");

这可能有帮助:

JTextPane.setKeymap(
  JtextPane.getKeymap().addActionForKeyStroke(
    KeyEvent.VK_V, InputEvent.CTRL_MASK,DefaultEditorKit.CopyAction));

您必须了解的是,击键 Ctrl + C 和 Ctrl + V 已经被 JTextPane 捕获,因此您的侦听器永远不会收到通知。

获得通知的最快方法是通过以下方式注册此操作:

myJTextPane.getActionMap().put(DefaultEditorKit.copyAction, myCopyAction);
//and
myJTextPane.getActionMap().put(DefaultEditorKit.pasteAction, myPasteAction);