Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (475)
Games in Android Showcase (106)
games submitted by our members
Games in WIP (530)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Converting a string to a keyCode  (Read 1763 times)
0 Members and 1 Guest are viewing this topic.
Offline cubemaster21
« Posted 2013-01-17 03:30:44 »

I'm trying to make a method of converting a string, such as "HOME" or "BACKSPACE", into it's corresponding keyCode. I know that there has to be some way to do this other than using a series of IF statements or a switch of some sort. I've done research and haven't been able to find anything that is really what I'm looking for. Does anyone know how this can be accomplished?

Check out my game, Viking Supermarket Smash
http://www.java-gaming.org/topics/iconified/28984/view.html
Offline HeroesGraveDev

JGO Kernel


Medals: 238
Projects: 11
Exp: 2 years


┬─┬ノ(ಠ_ಠノ)(╯°□°)╯︵ ┻━┻


« Reply #1 - Posted 2013-01-17 03:51:14 »

1  
2  
3  
4  
5  
If you only need it for key chars, then try:

[code
keyEvent.setKeyChar(keyChar);
int code = keyEvent.getKeyCode();


If you need it for HOME etc. you will need a way to link a String to an Int.

You could try a HashMap<String, Integer>
You would still need to define all the values, but at least it only requires
1  
int homeKeyCode = map.get("HOME");

Offline cubemaster21
« Reply #2 - Posted 2013-01-17 04:01:46 »

1  
2  
3  
4  
5  
If you only need it for key chars, then try:

[code
keyEvent.setKeyChar(keyChar);
int code = keyEvent.getKeyCode();


If you need it for HOME etc. you will need a way to link a String to an Int.

You could try a HashMap<String, Integer>
You would still need to define all the values, but at least it only requires
1  
int homeKeyCode = map.get("HOME");

That's sorta what I've got at the moment, I just figured that there had to be an easier way than adding each value in a for loop from a huge switch statement.

Check out my game, Viking Supermarket Smash
http://www.java-gaming.org/topics/iconified/28984/view.html
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline HeroesGraveDev

JGO Kernel


Medals: 238
Projects: 11
Exp: 2 years


┬─┬ノ(ಠ_ಠノ)(╯°□°)╯︵ ┻━┻


« Reply #3 - Posted 2013-01-17 04:05:04 »

There is a difference between a HashMap and a switch statement.

Anyway, you can get all the values for chars by using the other method I said.
All you need to do is work out whether it's a string or a char, then use the appropriate method. It's not clean, but it (should) work.

Offline cubemaster21
« Reply #4 - Posted 2013-01-17 04:05:59 »

No, it's not clean in the least bit. This is what I've got.
http://pastebin.java-gaming.org/18757668f3e

Check out my game, Viking Supermarket Smash
http://www.java-gaming.org/topics/iconified/28984/view.html
Offline actual

JGO Coder


Medals: 23



« Reply #5 - Posted 2013-01-17 04:22:29 »

Assuming you are only going to do this once at start up, you can use reflection and not really worry about the performance hit

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
// The map that will hold the conversion from codes to names
HashMap<Integer, String> keyCodesToNames = new HashMap<Integer, String>();

// converts names to codes
HashMap<String, Integer> keyNamesToCodes = new HashMap<String,Integer>();
     
try {
   
   // Get all of the fields in KeyEvent
  Field[] fields = KeyEvent.class.getFields();

   for (int i = 0; i < fields.length; i++) {

      String fieldName = fields[i].getName();

      // We only care about the field names corresponding to key codes
     if (fieldName.startsWith("VK")) {
         // Use reflection to get the actual key code value
        int keyCode = fields[i].getInt(null);
         String keyName = fieldName.substring(3);

         // Add the code and name values to the maps
        keyCodesToNames.put(keyCode, keyName);
         keyNamesToCodes.put(keyName,keyCode);
      }
   }
} catch (Exception e) {
   e.printStackTrace();
}
     
// Try it out      
System.out.println(keyCodesToNames.get(KeyEvent.VK_5));
System.out.println(keyCodesToNames.get(KeyEvent.VK_ESCAPE));
System.out.println(keyNamesToCodes.get("ESCAPE"));


* edit: cleaned up the code a bit.
Offline HeroesGraveDev

JGO Kernel


Medals: 238
Projects: 11
Exp: 2 years


┬─┬ノ(ಠ_ಠノ)(╯°□°)╯︵ ┻━┻


« Reply #6 - Posted 2013-01-17 04:37:25 »

What is this for?

Anyway, use actual's code.

Offline Best Username Ever

Junior Member





« Reply #7 - Posted 2013-01-17 04:39:55 »

If you only need it for key chars, then try:
1  
2  
keyEvent.setKeyChar(keyChar);
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.

@cubemaster21

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
getKeyText(i)
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.) Smiley The person you copied from is probably not much more experienced. It's pretty bad.

I doubt a
getKeyCode(String)
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.
Offline cubemaster21
« Reply #8 - Posted 2013-01-17 04:46:05 »

Well, I've been trying to make my own library that I can use with my own games and make things a lot simpler. I figured that adding a keyboard would be a good idea. I'm using strings because when I do my update logic for the game, it would look something like this:
1  
2  
3  
4  
public void tick(int delta){
    if(Keyboard.isKeyDown("SPACE")
        jump();
}

I didn't want to have to deal with KeyEvent. This altogether is starting to sound like a bad idea on my part....

Check out my game, Viking Supermarket Smash
http://www.java-gaming.org/topics/iconified/28984/view.html
Offline actual

JGO Coder


Medals: 23



« Reply #9 - Posted 2013-01-17 04:54:16 »

One thing you could do if you wanted is to use a map to separate the key codes from your game logic. For instance you could do:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
Map<String,Integer> keyMap = new HashMap<String,Integer>();

keyMap.put("JUMP",KeyEvent.VK_SPACE);

// In your keyboard class
public boolean isActivated(String key) {

   int keyCode = keyMap.get(key);

   // do logic to figure out if that key code is pressed.
}

// later on in your tick code.
public void tick(int delta) {
   if (Keyboard.isActivated("JUMP")) {
      jump();
   }
}


This way if you change your jump key from space to up arrow (or the player changes it), only the keymap changes. You don't have to change it every where in your code. Now the above code isn't perfect as Jump is only defined by one key (For instance "JUMP RIGHT" might require both space and right arrow) but it should help.

Also, you should probably use an Enum instead of string names. They are faster and the compiler will flag errors if you accidentaly use JUPM instead of JUMP.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Best Username Ever

Junior Member





« Reply #10 - Posted 2013-01-17 23:52:47 »

1  
2  
3  
4  
public void tick(int delta){
    if(Keyboard.isKeyDown("SPACE")
        jump();
}


That's no better than
Keyboard.isKeyDown(VK_SPACE)
. Definitely not worth it.
Or just do
if(Input.poll(JUMP_KEY) { ... }
.

Also, you should probably use an Enum instead of string names. They are faster and the compiler will flag errors if you accidentaly use JUPM instead of JUMP.

Definitely. You can also use your IDE to automatically find, highlight, or rename instances of the constant.
public static final int
s work, too. For some reason you can static import variables, but not enum constants... (Or at least in an old version of Java.)
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

ctomni231 (33 views)
2014-07-18 06:55:21

Zero Volt (29 views)
2014-07-17 23:47:54

danieldean (24 views)
2014-07-17 23:41:23

MustardPeter (26 views)
2014-07-16 23:30:00

Cero (41 views)
2014-07-16 00:42:17

Riven (43 views)
2014-07-14 18:02:53

OpenGLShaders (31 views)
2014-07-14 16:23:47

Riven (30 views)
2014-07-14 11:51:35

quew8 (29 views)
2014-07-13 13:57:52

SHC (65 views)
2014-07-12 17:50:04
HotSpot Options
by dleskov
2014-07-08 03:59:08

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:58:24

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:47:22

How do I start Java Game Development?
by ra4king
2014-05-17 11:13:37

HotSpot Options
by Roquen
2014-05-15 09:59:54

HotSpot Options
by Roquen
2014-05-06 15:03:10

Escape Analysis
by Roquen
2014-04-29 22:16:43

Experimental Toys
by Roquen
2014-04-28 13:24:22
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!