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

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

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

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

    我所追求的是一种更改JTextPane类的键盘映射的方法,但不能更改所有JTextComponent派生类的键盘映射。

    还是我应该在别处寻找?

    最佳答案

    恕我直言,a有点难以理解,但答案在这里:
    Using the Swing Text Package by Tim Prinzing

    根据源代码,文章的作者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);
    

    我的错误是将我的击键添加到getKeymap返回的键映射中,而不是将其传递给子级。恕我直言,名称addKeymap()令人困惑。它可能应该是createKeymap()。

    08-19 10:48