JTextComponent键映射

Ste*_*hen 4 java swing keymapping jtextcomponent

我需要创建一个派生自JTextComponent(从JTextPane,实际)的类,其中至少有一个默认键映射被更改.也就是说,在我特殊的JTextPane中,我希望">"键击执行操作而不是将该字符添加到文本窗格中,因为默认情况下会处理所有可打印的键入字符.

为了打破正常行为,有以下API:

  • JTextComponent.getKeymap()
  • Keymap.addActionForKeyStroke()
  • JTextComponent.setKeymap()

但是,我发现尽管这些方法不是静态的,但它们会影响JTextComponent我的应用程序中所有s 使用的键盘映射.没有简单的机制可以克隆Keymap,可能会解决问题,或者我错过了什么.

我所追求的是一种改变我的JTextPane类的键映射的方法,但不是所有来自JTextComponent类的键.

或者我应该在别处寻找?

Ste*_*hen 5

恕我直言,这有点难以理解,但答案就在这里: 使用Tim Prinzing的Swing Text Package

这篇文章的作者Tim Prinzing,我相信,根据源代码也是JTextComponent的作者,提供了一个我将评论的例子:

      JTextField field = new JTextField();
// get the keymap which will be the static default "look and feel" keymap
      Keymap laf = field.getKeymap();
// create a new keymap whose parent is the look and feel keymap
      Keymap myMap = JTextComponent.addKeymap(null, laf);
// at this point, add keystrokes you want to map to myMap
      myMap.addActionForKeyStroke(getKeyStroke(VK_PERIOD, SHIFT_DOWN_MASK), myAction); 
// make this the keymap for this component only.  Will "include" the default keymap
      field.setKeymap(myMap);
Run Code Online (Sandbox Code Playgroud)

我的错误是将我的击键添加到getKeymap返回的keymap,而不是让它给孩子.恕我直言,名称addKeymap()令人困惑.它应该是createKeymap().