问题
I'm in the process of developing a text editor that has a "macro system," where the user can reassign values to the keys on their keyboard -- so that when they press the letter a, it might print the letter "z" instead. (Really, it'll be used for math symbols, not other letters).
Can anyone get me started on the Java code to reassign a value to a key within a JTextPane?
If you need more details, let me know.
Thank you!
So far, this is what I have:
public void keyPressed(KeyEvent evt) {
//Called when a key is pressed.
//Intercept the key before the default value is printed.
//1. Suppress the original character. Do this in the KeyEvent object
//by setting the doit property to false in your listener if the key
//matches a macro.
jTextPane1.addKeyListener(new KeyAdapter() {
public void keyPressed(keyEvent event) {
if (event.getKeyCode() == KeyEvent.VK_A) {
//Perform an action when A is pressed and there is a macro.
if(macroA == true)
{
keyPressed.doit() = false;
}
}
}
else if (event.getKeyCode() == KeyEvent.VK_B) {
//Perform an action when B is pressed if there is a macro.
if(macroB == true)
{
keyPressed.doit() = false;
}
}
}
});
I'm working on how to implement it with "creating" the macro, checking to see if a macro exists.
If you have any more advice, I would appreciate it.
Thank you.
回答1:
I haven't done any Swing development in a while, but I think you're looking for a KeyListener. There's an example here: http://download.oracle.com/javase/tutorial/uiswing/events/keylistener.html
Your back end would need to map the key inputs with your macros and intercept the key input and insert the macro instead.
回答2:
If you want to change the character displayed in the text pane then you have two options (that I can think of)
a) rewrite the code that displays the text in the text pane b) insert a different character into the Document so that character will get painted
Option two is the easier approach.
For simple one to one key mappings you can just use a DocumentFilter.
For more complex key mappings, like using Ctrl+1, to enter a special character you would then use KeyBindings.
The Swing tutorial has section on both of these approaches. See "Text Component Features" and "Using Key Bindings".
来源:https://stackoverflow.com/questions/4730208/reassign-a-new-character-to-a-key-so-that-it-gets-printed-instead-of-the-defa