JTextComponent Keymap

1.6k Views Asked by At

I need to create a class derived from JTextComponent (from JTextPane, actually) in which at least one of the default key mappings is changed. That is, in my special JTextPane, I want the ">" keystroke to perform an action and NOT add that character to the text pane as, by default all printable typed characters are treated.

To defeat the normal behavior, there are the following APIs:

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

However, I find that though these methods are not static they DO affect the keymap used by all JTextComponents in my application. There is no simple mechanism by which a Keymap may be cloned which, presumably would solve the problem, or am I missing something.

What I am after is a way to change the keymap for my JTextPane class but not for ALL JTextComponent-derived classes.

Or should I be looking elsewhere?

2

There are 2 best solutions below

1
On

I would go for a specific Document instead, especially if you want your mapping to be valid just for an instance and not globally.

Here is an example of capturing keys and perform appropriate actions:

JFrame f = new JFrame();

StyledDocument d = new DefaultStyledDocument() {
   @Override
   public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
      if (">".equals(str)) {
         // Do some action
         System.out.println("Run action corresponding to '" + str + "'");
      } else {
         super.insertString(offs, str, a);
      }
   }
};

JTextPane t = new JTextPane(d);
f.add(t);
3
On

IMHO, aIt's a bit difficult to understand but the answer is here: Using the Swing Text Package by Tim Prinzing

The author of the article, Tim Prinzing, who is also, I believe, the author of JTextComponent according to source code, provides an example which I will comment:

      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);

My mistake was adding my keystroke to the keymap returned by getKeymap instead of letting it to the child. IMHO, the name addKeymap() is confusing. It should probably be createKeymap().