aspose file tools*
The moose likes Beginning Java and the fly likes creating a menu class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "creating a menu class" Watch "creating a menu class" New topic
Author

creating a menu class

David Patrzeba
Greenhorn

Joined: Jun 08, 2010
Posts: 14
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

Joined: Sep 16, 2008
Posts: 241
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.


SCJP 6, OCMJD 6, OCPJWSD 6
I no good English.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4492
    
    8

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

Joined: Oct 13, 2005
Posts: 40064
    
  28
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: creating a menu class