• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

creating a menu class

 
David Patrzeba
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm currently creating a class to handle menu options. So far I am able to create menu's with options ie:


And I have written the code in order to output the options so it looks like this:


So here is where I don't know if there is better method to implement what I want to do next, but essentially right now I take the user input and then I use a switch and case in a HandleMenu file. I don't think this is the best solution because it implies that I have knowledge of all the menu options.

I want to somehow include the method call in the Menu class so it would look something like this:


Does anyone have an idea on how I would implement this; I hope I was clear.

 
Martin Vanyavchich
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try using an enum. For those you always know all the options and can retrieve them with .values() function. Check this link or this one.
 
Matthew Brown
Bartender
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could encapsulate the function call in an interface. For example:

(That's using an anonymous inner class - there are other ways if you don't like them).

Then in the Menu class, store the MenuCall objects against the option numbers. When the option is entered, extract the MenuCall and call execute() on it. Your Menu class doesn't have to know anything about what the options are. That would do what it sounds you're looking for.
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot pass a method as an argument. Methods aren't first-class objects in Java™. What you would get is the return type from that method passed.

I presume you are running this from the command line; it is completely different if you use Swing.
I can think of several non-GUI ways to implement a menu. In addition to the use of an enum, you can enter the numbers and use a switch block. You can put the Strings and objects which will carry out the actions into a Map, and use the Strings as keys to retrieve the action objects.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic