If you only need it for key chars, then try:
int code = keyEvent.getKeyCode();
Bad advice. Key chars and key codes are completely separate concepts. The same virtual key can create many different possible chars or none at all. Setting one variable probably does not have an effect on the others. KeyEvent objects just hold those values. They are calculated somewhere else.
The map advice, on the other hand, is perfectly fine.
The answer depends on your level of experience.
Pro: Do you want the Java constant names? (Which could be read from a file or obtained using reflection.) Or a locale specific String? (Which can be solved by iterating through every possible keycode and possibly caching the result of
in a map. Or reading from a file, which would not force you to use one to one mappings. "Meta", "Super", "Windows", and "Apple" all refer to the same key, but getKeyText will only return one.)
Where do the Strings come from and what are they meant to be used for?
Noob: You are not supposed to use key codes and Strings that way. A key code is more valuable than a String. I would avoid using Strings. They aren't much help for programming logic. Mainly just user interfaces like key binding editors, if even that, where you could show the user which key they pressed. If you have a good reason for wanting Strings, then explain what that is because you were too vague. There are uses to justify such a reverse look up, but they would not necessarily use the same mapping that getKeyText would. If it were actually more helpful to use Strings than ints, then the String values you use depend on your application.
Edit: Too slow to post. Looking at your code, you are definitely a noob. (Magic constants are a dead give away.)
The person you copied from is probably not much more experienced. It's pretty bad.
I doubt a
function will help in the long run. It's better to use key codes. If you did need the function, you might call it once for each string used at the start of your program. You better explain your scenario.