• Post Reply Bookmark Topic Watch Topic
  • New Topic

Enum useage question  RSS feed

 
Warren Bell
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a situation where I pass a constant to a constructor. I want to use an Enum, but I am not quite sure how to. My code looks something like this:

public class KeyPressedBehavior
{
public final static String ENTER_KEY = "13";
public final static String ZERO_KEY = "48";
public final static String ONE_KEY = "49";
public final static String TWO_KEY = "50";
...

public KeyPressedBehavior(String keyPressed)
{
this.keyPressed = keyPressed;
}

private String keyPressed;
...
}

I am instantiateing KeyPressedBehavior like this:

new KeyPressedBehavior(KeyPressedBehavior.ENTER_KEY)

I am using this class to generate JavaScript that needs to know the ASCI decimal value of the key pressed.

How can I use an Enum instead of the messy constant code above, or can I?

Thanks,

Warren Bell
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can do something like this:

And then, in your other code, you just use the enum values:
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just one tip: use the constants defined in java.awt.KeyEvent:

However, you would be copying a lot of information already present in that class only because you're switching to an enum.

In this case, I'd just use the KeyEvent constants.
 
Warren Bell
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I didn't think about using the constants in KeyEvent. Well now I know how to use an Enum too.

Thanks for your response.

Warren
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!