• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Enum useage question

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can do something like this:

And then, in your other code, you just use the enum values:
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
The only taste of success some people get is to take a bite out of you. Or this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic