title: How can I perfectly simulate KeyEvents?
body: <p>How can I construct my own <code>KeyEvent</code> objects which perfectly (or very closely) match the ones I would receive from a <code>KeyListener</code> when the end-user types something?</p>
  
  <hr>
  
  <p>For example, I have a United Kingdom ISO keyboard layout and to type the <code>"</code> character I press <code>Shift+2</code>. If I record this on a <code>JFrame</code> with a <code>KeyListener</code>, I receive the following events:</p>
  
  <pre><code>java.awt.event.KeyEvent[KEY_PRESSED,keyCode=16,keyText=Shift,keyChar=Undefined keyChar,modifiers=Shift,extModifiers=Shift,keyLocation=KEY_LOCATION_LEFT,rawCode=16,primaryLevelUnicode=0,scancode=42,extendedKeyCode=0x10] on frame0
  java.awt.event.KeyEvent[KEY_PRESSED,keyCode=50,keyText=2,keyChar='"',modifiers=Shift,extModifiers=Shift,keyLocation=KEY_LOCATION_STANDARD,rawCode=50,primaryLevelUnicode=50,scancode=3,extendedKeyCode=0x32] on frame0
  java.awt.event.KeyEvent[KEY_TYPED,keyCode=0,keyText=Unknown keyCode: 0x0,keyChar='"',modifiers=Shift,extModifiers=Shift,keyLocation=KEY_LOCATION_UNKNOWN,rawCode=0,primaryLevelUnicode=0,scancode=0,extendedKeyCode=0x0] on frame0
  java.awt.event.KeyEvent[KEY_RELEASED,keyCode=16,keyText=Shift,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_LEFT,rawCode=16,primaryLevelUnicode=0,scancode=42,extendedKeyCode=0x10] on frame0
  java.awt.event.KeyEvent[KEY_RELEASED,keyCode=50,keyText=2,keyChar='"',keyLocation=KEY_LOCATION_STANDARD,rawCode=50,primaryLevelUnicode=50,scancode=3,extendedKeyCode=0x32] on frame0
  </code></pre>
  
  <p>I want to create a method which I would give the <code>"</code> as a char parameter, and it would return an array of the KeyEvents as listed above.</p>
  
  <p>My problems are:</p>
  
  <ul>
  <li><p>In the <code>KEY_PRESSED</code> and <code>KEY_RELEASED</code> events, <code>keyChar='"'</code> represents the character that was pressed (<code>"</code>), however the <code>keyCode=50</code> refers to the "non-shifted" ASCII value (aka <code>2</code>). I need to know how to get this non-shifted value from just the <code>"</code> character.</p></li>
  <li><p>This non-shifted value will also be different for different keyboard layouts. For example, the US ANSI layout requires <code>Shift+'</code> to type the <code>"</code> key, which means the <code>keyCode</code> would be 39 rather than 50.</p></li>
  <li><p>On some keyboard layouts, the shift key is required to type a key, but not on others. The <code>#</code> character for example requires <code>Shift+3</code> on US ANSI keyboards, but requires no shift press on UK ISO keyboards. I need to know whether I should simulate the shift press/release events and provide a shift modifier.</p></li>
  </ul>
  
  <p>Any insight on how to solve these problems would be appreciated. I should also note that using the <code>Robot</code> class cannot be used in my situation.</p>