问题
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 JTextComponent
s 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?
回答1:
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().
回答2:
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);
来源:https://stackoverflow.com/questions/11973135/jtextcomponent-keymap