Java drawings MVC - java

I am trying to create a game in java using several design patterns / principles. One of them being MVC. The situation is like this:
Model: Holds all game logic
Controller: Button interaction and list of GameElements (see code)
View: All GUI stuff including drawing.
Now, my game objects are all located under the Model, but for my drawing I've tried doing this (inside paintComponent)
ArrayList<GameElement> ge = FieldController.getElements(); // This is located under Controller
for(GameElement ge: GameElements)
{
graphics.setColor(ge.getColor());
graphics.fillRect(ge.x,ge.y,ge.width,ge.height);
}
Which works, but my question is: Where should the ArrayList of GameElements really be kept?
Is it okay to hold it in the control? Or should it be kept in the view?
I'm quite sure it should not be held in the model because then View&Model would be too tightly coupeled.

Your List<GameElement> belongs in the model. Upon notification, a listening view should decide how to render the element. In this context, the notion of loose coupling refers to the notification; the view still has to interpret what it learns from the model. In this simplified example, the model manages an abstract Piece having an attribute for color. The GUI view shown renders this attribute as an Icon having the specified color. In contrast, a text view might render the attribute as a String.

Related

Using the Model-View-Presenter design pattern for a Java Swing application

I'm working on developing a Java application for organising personal music collections that allows the user to search their digital music library with the help of textual lists displayed in a table, choose songs for playback and provide information about them i.e. something like Rekordbox (https://rekordbox.com/en/).
After conducting some research on how to design and implement such a system, I came across the Model-View-Presenter design pattern and from what I understood it is a pattern that allows flexible , reusable and test driven code to be written.
So to come to my problem:
View classes: Assume I want to have a Swing UI that consists of a JFrame which has 3 JPanels inside of it as separate view classes. i.e. MainFrameView with MenuBarView, TablePanelView, PlayerPanelView which are created inside the frame (which is a view class itself). Those panels have various Swing components inside of them such as JMenuBar, JTable, JButtons, JProgressBar.
Model classes: The two models I have are TableModel (used by the TablePanelView to display the user's music library and which stores the path to the directories of his/her songs in a List ) and PlayerModel (used by the PlayerPanelView to manipulate the the digital audio files that the user selects i.e play/pause/stop songs, fast forward etc.) The PlayerModel uses the selected by the user song directory to initialize itself.
So, my question is how can I implement the Presenter so that the different views (which use different models) are being able to communicate and share information between each other? Should I have a single Presenter to which the views talk or have a presenter for every view? If it's possible to have a single presenter how can that be achieved? If I have one Presenter for the MenuBarView, TablePanelView and PlayerPanelView and those views are contained in another view (which is the MainFrameView ) should I combine the presenters in some way, and if yes how?
If i were you I would try the MVC (Model View Control) pattern before trying MVP. It´s very similar but I would say it´s a bit easier to understand.
I wouldn´t create a own view for the MenuBar because you probably won´t create it dynamically. Just write a method in your MainFrameView where you initialize it and call that in the constructor of the MainView.
The model is a property of the item you use. Now if you want to create a Panel with a own model but also want to access the model from the MainFrameView you simply write a Getter/Setter for it. It looks like this in the MainFrameView:
public TablePanelView tpv;
public void initTablePanelView(TablePanelModel tpm){
tpv = new TablePanelView();
tpv.setModel(tpm);
}
So you can use the public methods getModel() or setModel() that you wrote in the TablePanelView to access the Model.
I hope that helped.

Would this be a suitable MVC chess (GUI) model?

I'm making a Java chess game as a uni project, and I'm basically getting the move from a player using a GUI.
My game has several classes, but the main classes are the Pieces, HumanPlayer and GraphicalDisplay classes.
What I'm basically doing is, when the HumanPlayer wants to make a move, it's currently using a class called PieceController, which is using a PieceModel class and the GraphicalDisplay classes as the model and view.
The problem is that I'm having to write code to set, for example, MouseListeners to certain cells in the chess grid (contained in an two dimensional array called cellHolder) in the Model class. This is because the code that contains adding listeners to cells also change state of the data, which is then used to display the game in the GUI.
This is causing a problem. The cellHolder object is created inside the GraphicalDisplay (GUI) class, but it's also used in the model and therefore the model is using data from the view.
I can't really think of another way of doing this without having to share (or pass as an argument) the cellHolder.
Any suggestions on how to improve the current MVC design?
Check this link http://www.tutorialspoint.com/design_pattern/adapter_pattern.htm
About Design Patterns In Java this one is called "the Adapter Pattern" .. It's basically a software design pattern that allows the interface of an existing class to be used from another interface

How should multiple classes be used for an application's different screens?

I have an application that is a Maths Game for kids. Since I'm in college, I've usually only had a god object for all my past projects but for this applciation I've split my code into multiple classes:
MathsGame.java: main class which initialises components and constructs and controls the UI.
DiffScreen.java: contains methods for use on the difficulty selection screen.
GameScreen.java: contains methods for use on the game screen.
EndGameScreen.java: contains methods for use on the end game screen.
MigJPanel.java: extends JPanel and sets layout to MigLayout and adds a matte border.
Each screen that the 3 XScreen classes control is simply an instance of MigJPanel and screens are switched to using a CardPanel container JPanel.
I'm wondering how I can divide my code to each class so that they are properly abstracted but I'm not entirely sure how to approach this.
Should my 3 screen classes be extending from my MigJPanel so these then can be instantiated?
So instead of having my DiffScreen, GameScreen, and EndGameScreen classes solely containing methods related to each screen which are then called from MathsGame, each screen will control itself within its own class.
If yes to the previous question, should the UI components for each screen be made inside that screen's class?
At the moment, all components for each of the three screens are created in my MathsGame constructor. This makes the connection between a screen and the class which 'controls' (I use this word very lightly at the moment) it even further apart. So each screen is just an instance of MigJPanel whose components are constructed in MathsGame. The only relation the EndGameScreen class—for example—has to the End Game screen is that when the MathsGame causes the End Game Screen to be displayed, anything done there makes a method in EndGameScreen be called from MathsGame.
I hope I explained myself well. If not, leave a comment and I'll clarify. Any help would be greatly appreciated!
Yes
Yes.
Focus on self containment and maintain areas of responsibility. It is the responsibility of each UI screen to manage it's content, no one else, in fact, you should guard against allowing unrestricted modification to these components and provide access only through managed methods indirectly (setters and getters), which allow the modification of the properties you want to be changed, and not simply providing the component via a getter, this prevents problems with people removing components you don't want removed, for example.
You could also use interfaces to maintain common functionality if required, so if the MathsGame really only wants to deal with a certain amount of the information/functionality, you can use an interface that all the other screens use which will simplify the process, as the MathsGame only needs to know about the class that implement the interface and not EVERY thing else that might be going on...as a suggestion..
Also, where should I put the code for switching between screens?
From my perspective, it's the responsibility of the MathsGame game to determine when and to which screen should be shown. What I would normally do, is provide some kind of notification process that the current screen can ask the MathsGame to switch screens, maybe via a listener or other agreeded interface. This would mean that each screen would need reference to MathsGame.
Instead of passing it (MathsGame) directly, I'd create an interface that MathsGame would implement (say NavigationController), which defined the calls/contract that each sub screen could use (nextScreen/previousScreen) for example.
Take a look at Model-View-Controller for more ideas

how to implement MVC pattern for word guessing game?

I have some working code for the word guessing game. But I fear it does not confine the design rules especially the MVC pattern. The attached image is my GUI currently. I am throwing around objects from one class to another and I hear that it is a bad style. while I agree with that, I am not able to come up with good MVC pattern approach for the word guessing game or the Hangman commonly called.
The main application will have some like this:
public class Application {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
runApp();
}
});
}
public static void runApp() {
Model model = new Model();
View view = new View(model); //not sure if this correct, some suggest it is valid and some not
Controller controller = new Controller(view, model);
}
}
how would I approach this?
The GUI as seen in the attached picture would be the View Class. This includes all JButtons, Textfield, borders, labels etc. Attach actionlisteners to JButtons in the View class
The controller will pass the events to the model. for example, if some letter buttons are clicked, it would pass that letter "A" is clicked to model and the model will either send instructions to controller to update view or it will update view directly. from my understanding of the MVC pattern, the model class must be implemented and tested separately from view and controller. I do not understand how I can achieve this here. I have complete code available. I need to refactor to confine to MVC pattern. kindly pass on your suggestions.
I think one of the areas you are getting confused over is "responsibility". What is each component responsible for and what can it actually do.
The problem isn't that you are passing Objects around you program, but more that the objects you are passing are exposing parts of your application that the recipient has no business knowing about or should be allowed to manipulate.
What I mean by this is, if you were to pass the "buttons" panel to the "guess" panel, because you wanted to have the ability to allow the "guess" panel detect when a button was clicked, you've exposed the "buttons" panel to an area of your application that has no right to actually see it.
What's stopping the "guess" panel from removing components? Nothing...
Instead, we should use interfaces which determine what each part of the application can and can't do and what information is available to it.
This is where you model comes in. The model determines what information is available, how it can be accessed and what events might be triggered to notify interested parties that the model has changed.
For example. Your "buttons" panel would tell the model that the user has made another guess (in response to the user pressing the button). The model would then raise an event, which would notify the "guess" panel that a change has occurred. The "guess" panel then would update it's state accordingly, asking the model for the information it needed in order to represent the current state of the model (as far as it was responsible for).
You could take a look at
Code to Interface, Access by name and Instance Data
Program to an interface
Now, with the MCV pattern, the view must be able to see the model, the controller must be able to see the view and model and the model doesn't care.
The controller is listening for changes to the view (ie user interactions), which it passes to the model. The model fires notifications about changes to it's state and the view responds to those changes by updating itself as required.
For example, the use clicks a button on the "button" panel. The "button" panel's controller detects this event (probably via an ActionListener), it process this action and updates the model.
The model updates it's internal state and fires some kind of event.
The "guess" panel detects this change in the model (via some kind of listener) and updates it's view accordingly (update the guess's and the image as dictated by the model).
Now, remember, Swing doesn't use a pure MCV pattern, it's controls (ie buttons) are both the controller and the view, so just be careful when playing around with these...
I would start with a HangManModel interface which defines all the properties you want to expose, such as the guesses, the "secret" word and perhaps the number of incorrect guesses made and the state of the game (win or lose) for example.
I would also define the listeners that might be registered to the model, which describes the events that this model can generate. You could use a PropertyChangeListener or even a ChangeListener or define your own, based on your own needs, for example...
public interface HangManModel {
public void addGuess(char guess);
public char[] getGuesses();
public String getSecretWord();
public int getState(); // running, win or lose
public void addChangeListener(ChangeListener listener);
public void removeChangeListener(ChangeListener listener);
}
Now this is just an example, personally, I might be tempered to hide the secret word and expose properties about it (like it's length for example). You could also be tempted to provide a setter for the secret word, so the model could be reset...
This would represent the "heart" of your application, around this, you would build your views and controllers.
EDIT : Working example of MVC (netbeans project, made by me) is download here or download here. Who does not know netbeans : in dist is executable .jar file and in src are sources.
It shows MVC pattern with two different views. On the left, you can left or right click to create circle or square and on the right you can see these squares and circles in table. You can change value (like size or position) of square or circle in table and it is updated into model which updates view so on the left you can see how that square or circle moved or resized.
You have good approach, but you got few things wrong. This is a basic, simple model of MVC :
As here you can see, the model DOES NOT send anything into the controller.
How to build MVC application? Mabye better start with the model. The model should have everything except the input/output handling. All the data, all the logic.
So you should have 3 main classes : Controller, View, Model.
For example you just create form with button which in each hit add one "A" letter into the middle of form.
In View class, you have update method, which paints and/or repaints the count of "A" letters into the form.
When you hit the button, it jumps into the method buttonClicked. This calls method on controller, saying that controller what just happend.
Controller see that and manipulates data in the model (in this example calls the method addA). After this, model should know that he was changed, so he call update method on the connected view class which repaints the count of "A" printed in the middle of form.
Addition
You can have multiple views for one model! We can add one more view, which in top-left corner of form prints the number of "A" used. Model can have list of view instead of just view and when changed, he just updates all of them.
Pseudocode
public class Application {
private Model model = new Model();
private Controller controller = new Controller();
private View view = new View();
public Application(){
model.registerView(view);
controller.registerModel(model);
view.registerController(controller);
}
}
Interestion question... So far I heard about MVP and MVVM design patterns used whithin desktop apps, but I have never seen MVC for this type of apps. However, I just took Spring MVC (the best java web framework) and tryed to apply it on desktop apps.
I would create a front controller that handles all events for the app.
This controller gets an event and sends it to EventResolver.
EventResolver returns back the name or something of a method and class which will play a "controller" role to the front controller.
After the front controller creates an instance of this class and calls a method.
In the method body you call some business logic and return model and id for ViewResolver to the front Controler.
6 Again the front controller analyzes the result and calls an approperiate ViewResolver.
Yes, this is how spring MVC works and I just copied it) But why not to use the best!
There's lots of different flavors of MVC, but they all share the same general idea.
The first thing to understand is exactly what the model is. The job of the model is to handle all the logical code. So in this case, the model will track which letters have been guessed, what the word to guess is, whether the game is over, and how many pieces of the stick man are showing.
Basically, you should be able to simulate the game in its entirety just from function calls into the model.
There's a few ways to pass information from the model to the view. The view could poll the model periodically to see if anything has updated. This method is not very elegant. A simple way that is often effective for small-scale projects is to pass a View object into the Model object and whenever anything changes in the model, refresh everything in the view. It's no big deal for a smaller UI to do this. Finally, you can create a Listener registration system (Observer pattern) to have specific parts of the View subscribe to specific events in the model. This method is what I've done for larger UI projects.
The controller's job is to pass user input to the model. For this reason, the controller and view can often be defined in the same classes. This is okay! It's much better to have your JButtons have a click method that calls the model directly rather than telling some Controller class to pass it on to the model.

MVP multiples views combine to form an overall view

The GWT documentation comes with a tutorial on how to utilize the MVP pattern here. In this example, there are two views, and each replace the other as per the user action.
In these rather simple views, it didn't hurt much to cram all widgets that view has in one single class (view) only. But for a complex view, one would like to create individual views for components (with a corresponding presenter for each such component view), then combine those views into the overall views (this combined view may or may not have a separate combined presenter, since all sub-views already have corresponding presenters). Somewhat similar to creating individual widgets in separate classes that extend Composite, calling initWidget on them, and using them like mainPanel.add(new subPanel()) in the main panel.
So is it possible to do such thing in MVP pattern in GWT?
No, if you do so the entire DOM load in a single shot,even though you put if else conditions inside .
When building large applications with GWT,Using MVP and code splitting is a must – otherwise,
the entire application (i.e. JavaScript bundle) is downloaded in one chunk on the initial
load of the application, which is a good recipe for frustrated users!
By using standard MVP you can
Isolate of User Interface from Business tier
Easily interchangeable Views (user interfaces)
Ability to test all code more effectively
I suppose you are expecting like below
public class MainPageView extends ViewImpl implements MainPagePresenter.MyView {
#UiField
public HTMLPanel mainMenuPanel;
#UiField
public HTMLPanel mainContentPanel;
#UiField
public HTMLPanel mainFooterPanel;
.
.
.
.
.etc
Yes instead of panels as shown above , you can also use classes which have some elements inside.
Update:
To mainMenuPanel you can add your class like mainMenuPanel.add(new MyheaderClass()).
Where MyheaderClass extends of Panel or Widget .So that the all elements in the Class add to the mainMenuPanel
Inside your MyheaderClass class you may add labels, buttons ...etc by using this.add(mybutton)..etc

Categories