How to go about display multiple "Menu" classes in java - java

Hi all I am relatively new to OOD and Java hence am not sure how to do this properly.
Currently I need to create an application (console/command prompt based) that involves going through a series of so called "menus" where the application will display your choices and you enter 1/2/3/4 etc. My professor told me to break up my boundary class (the class where all the display of choices is in) because it's too long (400+ lines).
Now comes the problem. If i were to break it up, I would have to keep creating new object classes to call on the different menu in different classes. For example:
Let say I have MainMenu, FoodMenu, DrinkMenu. So my main method will create a MainMenu object to call displayMenu(). From there, if I want to navigate to the food menu, I have to create another FoodMenu object and call displayMenu() under it again. Further along the codes, if i want to navigate back to the main menu, I would then again have to create the MainMenu object again and call displayMenu.
The above method would have so many variables waiting to be garbage collected and a total waste of memory. Is there another solution around this? Thank you very much in advance.
Hamlyn

Make all your menus either extend an abstract class (okay) or implement an interface (better), if you're not already doing that.
As for how to get to the menus, you can just store one of each type of menu in a menu array or some other collection (for example, a Map if you want to be able to look them up using a string or other object). Have that collection be globally accessible (static in some public class) and then you can display the same instance of a menu each time you need it.

First of all, garbage collection problems happen when you have thousands of objects floating around, not... three. So don't even worry about that.
But in general, your thesis that you need to recreate all those objects is flawed. You only need one of each, and they simply need to be able to get access to references to one another. For example, each "displayMenu" method might take a Menu as an argument; that displayMenu() method would set things up so that the "return to previous menu" option invokes the Menu that was passed as an argument.

As discussed in How to Use Actions, the Action class is a convenient way "to separate functionality and state from a component." This example creates a menu of recent files using instances of the RecentFile class. A similar class for each of your MainMenu, FoodMenu, DrinkMenu might be a way to encapsulate related menu items.

Related

Java ActionEvent in Different Class

been trying to solve this problem for over a day now, and throwing in the white flag now. Taking this class at UMUC, and it's pretty much a self-study curriculum without any help so I really appreciate being able to ask this question here.
Just going to ask this question conceptually, because I can't even get my head wrapped around the concept.
I have a GUI class (subclass of JPanel) that creates a button. In the GUI class, the button uses ActionListener to recognize when it is clicked and performs validation tests on a textfield. So far so good!
Now, after the validation tests -- which ensure the input in textfield is numeric, I want to use this input to add to a variable in a different class (called Account).
In the third class, which includes main method -- I have created two instances of Account class: checking and saving, as well as Frame and adding GUI to the frame.
Problem:
(1) How do I trigger the add method in account class when button in GUI class is clicked?
(2) How do I ensure it applies to the specific instance of the Account class, i.e, either checking or saving?
There are a number of ways you might be able to do this. One would be to provide a ActionListener property to your JPanel, which you would then trigger once you've validated the input from the button. This a basic observer pattern (and you're already using it on the JButton).
The problem is then how to get the information from the panel. You could provide getters on the panel, but this begins to tighten the coupling in your code.
A slightly better solution might be to provide your own listener/observer interface which you could then pass the information you want from the GUI to the listener, further de-coupling the API
I'd avoid passing the Account to the GUI if possible, unless it has some reason to actually use/modify the account, it's best to keep it decoupled of the responsibility, the GUI's responsibility is to get and validate the information as best as possible and pass the processing on to the observer/listener.
In this case, you just need to wrap the listener/observer around a particular instance of the account, so when it's triggered, it's operating on the correct account

Most efficient practice to access objects in other classes: Java

I am currently creating a dungeon crawler. I handle all of the dungeon generation, collision box generation, treasures and enemy generation, and player generation in one class called Dungeon. Each of the objects created in the dungeon class has a getter.
In the Main class, I am using an animation timer to handle all of the updates from the player moving, opening treasures, etc. This requires access to many of the objects created in the Dungeon class.
I am trying to better understand the use and benefit of object references in Java. My question is: What is the more efficient method to access the variables in the Dungeon class (or any other class for that matter) since I am accessing them hundreds or thousands of times?
For example, all of the treasures in the dungeon are in an ArrayList variable that is a member variable of the Dungeon class. So, I can retrieve that array list in my Main class like this: dungeon.getTreasureList(). If I need to get a specific item in that ArrayList I could use: dungeon.getTreasureList().get(i) where i is the index of the treasure object I want. This is fine for short calls (organizationally speaking) but it gets really messy with longer calls like so: dungeon.getPlayer().topIntersects(dungeon.getCollisions().getWalls())
Alternatively, I could create a reference to the treasureList in my Main like this: ArrayList<Treasure> treasure = dungeon.getTreasureList(). Then, if I need a specific object in the ArrayList I can call: treasure.get(i). This can clean up the long call above to something more like this: player.topIntersects(collisions.getWalls());. This is much easier to read and, as a result, I favor this method a bit more.
Disregarding the organizational benefits, is it a better practice to create a reference to access a variable to access information, or use the longer form and getters (like thisdungeon.getTreasureList().get(i))?
It would seem, that by creating a reference for player and collisions in the call dungeon.getPlayer().topIntersects(dungeon.getCollisions().getWalls()) I am saving two function calls by using player.topIntersects(collisions.getWalls());. Namely, one function call to dungeon.getPlayer()and one call to dungeon.getCollisions().
Since this is being called thousands of times while the game is running, it seems safe to assume I am saving many thousand function calls to dungeon.getPlayer()and dungeon.getCollisions(), resulting in a more efficient code. Am I right in this assumption?
EDIT: Trying to make the question more objective and less opinion based and corrected misleading phrasing
My opinion is that this question will be closed soon, because it's too opinion-based.
But if I did offer my opinion I'd say that letting classes access private collections and then operating with them is poor encapsulation.
Better to hide those details and provide methods to give the information you want without giving away the private details.

How can I access arraylist from one jframe to another jframe

I am relatively new in Java. In one of my project I have three jframes. They are Menuframe,that has list of menus; LoadDatafromExcelframe, that is use to select and read data from Excel file; and ShowDataFrame, that is use to display data that I read in LoadDatafromExcelframe. Actually its part of a big project. not the whole project! At the beginning of my project I am reading Excel file and load all the data in arraylist. Till this point I am good. Now I want to click the ShowDataFrame from the menulist to display the data that I have read in the LoadDatafromExcelframe. If I can access the arraylist then I think I can move forward. My question is "How can I access arraylist from one jframe (ShowDataFrame) to another frame(LoadDatafromExcelframe)?"I am using Netbeans IDE.
private void jMenuItemShowDataActionPerformed(java.awt.event.ActionEvent evt) {
showDataFrame.setVisible(true);
}
The key issue has little to do with JFrames or Swing in fact, but is simply one of passing information from one object to another. The only way Swing gets involved is if you want to pass this information in response to an event of one sort or another.
The solution is usually one of simply giving your classes appropriate getter and setter methods, of separating out your "model", the logical portion of your program, from your "view", the GUI portion of your program, and of using some sort of listener or observer type interface (such as can be obtained via Swing event listeners) to notify one class when the other is ready to push or pull information.
More general recommendations:
Avoid making anything static that does not need to be static. That is a quick solution that usually causes more pain in the long run as it makes your code very hard to enhance later and to test.
Avoid using lots of JFrames. Most professional GUI's have but one master window, one "JFrame" if you will. Often it is better to swap views in this JFrame such as with a CardLayout or with tabbed panes if needed. Also information that needs to be obtained in another window in a modal fashion can be displayed in a modal dialog.
Get a good book on OOPs basics as it applies to Java programming, such as Bruce Eckel's "Thinking in Java".
And get a good book on use of design patterns with Java such as Head First Design Patterns. These two concepts are key to moving ahead in Java.
Avoid using code generation utilities such as NetBean's form creation utility as it shields you from learning Swing specifics, and hinders your ability to learn to create complex Swing GUI's. Sure, use these tools once your a Swing journeyman, but until then, use the Swing tutorials to learn the library and code by hand.
For more specific advice, you will need to provide more details and provide more code.
Edit 2
More advice based on your post:
In one of my project I have three jframes. They are Menuframe,that has list of menus; LoadDatafromExcelframe, that is use to select and read data from Excel file; and ShowDataFrame, that is use to display data that I read in LoadDatafromExcelframe.
This looks to be better implemented creating 3 JPanels and not 3 JFrames. Then you could display the JPanels as needed in a single JFrame using a CardLayout to help you swap them.
Actually its part of a big project. not the whole project! At the beginning of my project I am reading Excel file and load all the data in arraylist.
This ArrayList should not be "read into a JFrame" but rather the data belongs in a non-GUI class, one of your "model" classes to be exact. Then the view classes, your GUI code can ask the model for this data whenever necessary. Read up on Model-View-Control program design on this site to learn more about this useful pattern.
Till this point I am good. Now I want to click the ShowDataFrame from the menulist to display the data that I have read in the LoadDatafromExcelframe.
Here using MVC structure, one of your "view" classes, the one holding the "menulist" should notify the "control" class that your code needs the ArrayList data held by the "model" class. This could all be done by having the Control class hold references to both "model" and "view" and having the "view" class hold references to the control thus allowing communication between classes.
You can change your ArrayList in static an public in the properties of the object then just call the name of te class who contains de ArrayList and call the ArrayList and use it wherever you want.
Something like this:
JFrame1.ArrayList1.add("some stuff");
Obviously doing this in the JFrame2 class where you want to call the ArrayList

Java E-Shop project

So I have an exercise about creating a functional e-shop with a minimal CMD UI. I have certain instructions and rules to follow while creating this and that's what makes it so difficult for me.
So firstly I have to create a class ierarchy, at the top of which stands the general Product.class and then below that the sub-classes Motherboard, CPU, GPU etc. Each of these sub classes contain their respective constructors. However, in the description of my exercise it isn't stated which items are going to be avalaible for immediate sale or should be ordered. Thus, I think that I'm supposed to choose these randomly meaning that I will have to create each and every one of these 'objects' by calling their constructors, like Motherboard mb1 = new Motherboard(motherboard info). Is there another way of implementing this? Because it seems like it's not the best way.
Now for my problem, say I have the required objects created and through the UI and consecutive questions the user will choose what product to buy, how am I going to 'transfer' this chosen object to my Sale.class so I initiate the sale and go on with the program?( The sale class has to print the item's info which is stored in its object and then reduce the items quantity from the shop's reserve)
Thanks in advance!
Your sale class should have a reference to the listed items. This probably should be a List or a Set.

Is there a design pattern that can help configuring commands on a generic display?

I have a display object that displays a list of Users and provides a menu for acting on that list - adding new users, adding them to groups, deleting them, etc. Right now the display configures its own menu, so it can add a menu command like doCreateNewUsers(). Unfortunately, this means that every instance of the display always has the "create new" option.
I want to configure the menu differently for different instances of the display - in the "Users" tab, it should include the "create new" option, and in the "Groups" tab, it shouldn't. My first thought was to externalize the menu, so that I could configure it differently. The problem is that then I lose the ability to call the private doCreateNewUsers() function!
Is there a design pattern for this situation? I don't like the idea of making doCreateNewUsers public because it shows a dialog that shouldn't be triggered by external classes. I could make the display abstract, so that I could define the menu in anonymous subclasses, but that kind of messes up the way I reuse widgets right now - I'd like to configure the menu after the display has been created and initialized. I'm hoping there's some industry-standard way of dealing with this!
It sounds to me like you could possibly use the Strategy Pattern in this case.
The display can configure its own menu but only if the action can be encapsulated in the command associated with the menu item. Once you set it up like that then you can add and remove items from the menu and they won't need access to the private methods, as they will have access to the command that is responsible for the action.
I think the command pattern is your friend here.
Once you have the command objects you can use those to create the menu items and provide the methods to execute the actual commands.
If you are just adding a list of User objects the passing the command objects might make more sense. If you are passing an object which represents a collection of users the it might make sense to add a method to expose the command objects. If this is the case then you should probably make your objects implement an interface to give access to the command objects, something like:
public ICommandProvider
{
ICollection<ICommand> GetCommands();
}
then a command could be:
public ICommand
{
String GetMenuText();
void Execute();
}
Having the object that is being displayed responsible for returning the commands makes it easy to have the commands have a reference to the thing being displayed so they can modify it (add elements or remove elements for example).
obviously the exact details will depend on your situation, but something like that should allow you to configure your display's menu options without your display needing to know about the details of what is being done. You'll probably need to refresh the display after a command.

Categories