BUG: java.awt.event.KeyListener.keyTyped Method Does Not WorkID: Q190301
|
The methods java.awt.event.KeyEvent.setKeyChar and java.awt.event.KeyEvent.consume have no effect on the AWT control when called from within the java.awt.event.KeyListener.keyTyped method.
The workaround is to move the event handling from the keyTyped method to the keyPressed method.
Microsoft has confirmed this to be a bug in the Microsoft products listed at the beginning of this article.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class TestKeyTyped extends Applet
{
TestPanel myTestPanel;
public void init()
{
myTestPanel = new TestPanel();
add(myTestPanel);
}
}
class TestPanel extends Panel implements KeyListener
{
TextArea myTextArea;
TestPanel()
{
setLayout(new BorderLayout());
add("West", new Label("Lower case \'a\' should change to upper "
+ "case \'A\' and \'%\' should be consumed:"));
myTextArea = new TextArea(1, 25);
add("Center", myTextArea);
myTextArea.addKeyListener(this);
}
public void keyTyped(KeyEvent e)
{
char ch = e.getKeyChar();
if (ch == 'a')
{
e.setKeyChar('A'); // Bug: Has no effect within
// keyTyped
}
else if (ch == '%')
{
e.consume(); // Bug: Has no effect
// within keyTyped
}
else
{
e.setKeyChar(ch); // Bug: Has no effect within
// keyTyped
}
System.out.println("Modified event to be: "+e+
" Consumed:"+e.isConsumed());
}
public void keyPressed(KeyEvent e)
{
// WORKAROUND
// Cutting the above code from the keyTyped method
// and pasting it here will cause the setKeyChar and
// consume calls to work.
}
public void keyReleased(KeyEvent e)
{
}
}
<applet
name="TestKeyTyped"
code="TestKeyTyped"
width="600"
height="50"
align="Top">
</applet>
For the latest Knowledge Base articles and other support information on Visual J++ and the SDK for Java,
please see the following pages on the Microsoft Technical Support site:
http://support.microsoft.com/support/visualj/
http://support.microsoft.com/support/java/
© Microsoft Corporation 1999, All Rights Reserved.
Contributions by Adele Hunter, Microsoft Corporation
Additional query words: KeyListener keyTyped KeyEvent TextArea setKeyChar consume
Keywords : kbcode KbAwtPkg kbJava kbSDKJava300 kbSDKJava310 kbSDKJava320
Version : WINDOWS:2.0,2.01,2.02,3.0,3.1,4.01
Platform : WINDOWS
Issue type : kbbug
Last Reviewed: July 9, 1999