In Java, when a key is pressed such as a letter, how do I prevent the key from outputting the letter that it is assigned to a jTextPane? (Similar to how do game developers suppress the normal functions of the keyboard when a part of their application is in focus).
When KeyEvent.consume() doesn't do the job alone, is there another way?
I'm a fairly novice programmer compared to other people o开发者_运维百科n this board, so please be patient with me. Any examples would be appreciated. I'm eager to learn. Thank you very much.
Assign custom DocumentFilter to the document from the JTextPane. You can intercept the insertString() and skip unnecessary input. It's better than key listener if you should also skip the same chars from pasted content.
This code is just a sample, I hope this will prevent A to Z getting entered , but does not cover all scenarios such as Shift,Ctrl and Alt presses.
JTextPane textPane = new JTextPane();
textPane.addKeyListener(new MyKeyListener());
public class MyKeyListener extends KeyAdapter
{
public void keyPressed(KeyEvent key) {
int i = key.getKeyCode();
if (i >= 65 && i <= 90)
{
((JTextPane)event.getSource()).cancelKey();
}
}
}
精彩评论