Reputation: 61
With the code below we have two behaviors, typing Til(~) character key.
On jdk 1.8.0_101 are printed character => Til(~)
On Jdk 1.8.0_171 are printed => Undefined() character.
I search on google and oracle documentation, but not found nothing about this.
Apparently it's something recent.
Any Ideia?
public class Sample extends JFrame {
private javax.swing.JTextField jTextField1;
public Sample() {
setSize(200, 80);
setLocationRelativeTo(null);
jTextField1 = new javax.swing.JTextField();
jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
System.out.println(evt.getKeyChar());
}
});
add(jTextField1);
}
public static void main(String[] args) {
new Sample().setVisible(true);
}}
Upvotes: 0
Views: 1505
Reputation: 61
Using the keyTyped did not work because getKeyChar() also returned me Undefined char. So I do a workaround below on KeyPress.
public void keyPressed(KeyEvent evt) {
if (JAVA_8 && evt.getKeyChar() == KeyEvent.CHAR_UNDEFINED) {
callKeyPressedEvent: {
switch (evt.getKeyCode()) {
case 129:
evt.setKeyChar(((evt.getModifiers() & KeyEvent.SHIFT_MASK) == 1) ? '\u0060' : '\u00b4');//` and ´
break;
case 131:
evt.setKeyChar(((evt.getModifiers() & KeyEvent.SHIFT_MASK) == 1) ? '\u005E' : '\u007E');//^ and ~
break;
case 135:
if ((evt.getModifiers() & KeyEvent.SHIFT_MASK) == 1) {
evt.setKeyChar('\u00a8');//¨
break;
}
default:
break callKeyPressedEvent;
}
processKeyEvent(evt);
}
}
Upvotes: 0
Reputation: 374
According to the documentation of getKeyChar()
method,
Returns the character associated with the key in this event. For example, the KEY_TYPED event for shift + "a" returns the value for "A". KEY_PRESSED and KEY_RELEASED events are not intended for reporting of character input. Therefore, the values returned by this method are guaranteed to be meaningful only for KEY_TYPED events.
So if you simply want to report the character typed, you should use the keyTyped()
instead of keyReleased()
. It worked for me. Here's the code for keyTyped()
method:
@Override
public void keyTyped(java.awt.event.KeyEvent evt){
System.out.println(evt.getKeyChar());
}
Upvotes: 1