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
Related
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.
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.
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.
GWT has a lot of similarly-named (and seemingly similarly-purposed) types:
Widget
AcceptsOneWidget
Composite
IsWidget
SimplePanel
When/where is it appropriate to use each of these? What is their relationship to the RootPanel?
Let's first separate interfaces from classes.
Interfaces are great for mocking (thus allowing for testing your app without the need for the sluggish GWTTestCase):
IsWidget: when all you need is a handle on a widget, without depending on the Widget class. This is typically used with MVP as a way to represent the view.
AcceptsOneWidget: when you need a placeholder for a single widget (in the form of an IsWidget). This is typically used with Activities, to insert the view (IsWidget) into the given slot (AcceptsOneWidget).
The classes you list all extend Widget, so they rely on JSNI and (most of the time) need to run in a GWT environment (for unit tests, that means a GWTTestCase):
Widget: the base of all widgets. Implements IsWidget returning itself from asWidget().
Composite: a base class when you need to create a widget built from other widgets while hiding their implementation. While you could extend an existing widget, it's generally better to hide it inside a Composite so you only expose the API you need/want to expose. Composite is about "composition rather than inheritance" and encapsulation. Examples of composites in standard widgets include TabPanel (built from a TabBar and DeckPanel), DateBox (built from a TextBox and DatePicker in a PopupPanel), ValueListBox that wraps a ListBox or ValuePicker that wraps a CellList. In many cases, given that panels accept IsWidget children, you could simply implement IsWidget rather extend Composite, but it's sometimes useful to have a true Widget.
SimplePanel a panel that implements AcceptsOneWidget, useful as a slot when using activities (but you could also easily implement AcceptsOneWidget to insert into any kind of panel)
That being said, Google recently open-sourced GWT-Mockito that plugs Mockito into GWT.create() and uses classloader magic to rewrite JSNI methods and remove final modifiers so you can directly use widgets in tests without the need for GWTTestCase or MVP.
So, all in all, it depends how you approach your code, how you architecture your app. If you use MVP, stick to depending on interfaces only (IsWidget, AcceptsOneWidget) in your presenter so you can easily mock your view in your tests.
Otherwise, or if you want a "simplified MVP" where the view is a UiBinder template, try GWT-Mockito for your tests and directly use widgets.
Of course, you can mix both approaches in the same application. And in any case, build your own widgets as Widgets for low-level things (rarely needed), and Composites or IsWidgets for everything else, rather than extending existing widgets.
You have got all mixed up.
Widget: It allow you to interact with the users. (e.g. Button)
Panels: These are widgets that can contain other panels/widgets. Can be referred as container of widgets.
AcceptsOneWidget: Implemented by panels which will accept only one widget. (e.g SimplePanel)
Composite: A type of widget that can wrap another widget, hiding the wrapped widget's methods. The composite is useful for creating a single widget out of an aggregate of multiple other widgets contained in a single panel.
IsWidget: An interface implemented by almost all known widgets. It Provides access to that widget.
SimplePanel: A panel which contains only one widget.
RootPanel: Is the base panel to which all other panels are added.
I'm developing this application where you can put text and drawings in a page. My application is in MVC pattern, and I need all the model parts, text and shapes to be of the same notion. They all extend an abstract ReportElement clas, for example.
But the problem is I crate a JPanel for every shape in the page, but to handle text I need to use JTextArea or something. To render the elements the View directly gets the report elements list from the Model and draws one by one. How can I distinguish a text element without hurting the MVC pattern.
I mean, it's impossible, right? I don't know, any ideas?
I think you're looking for the "Factory Pattern"
You need to have a wrapper method that returns a JComponent based in your own ReportElement conditions.
I would handle this situation by building a factory method that produces the right type of Swing component for any given ReportElement, like this:
public static JComponent buildViewForReportElement(ReportElement element)
Inside this method, you will need to actually inspect the ReportElement objects to see what type of component to build. This inspection might mean checking a field or a flag on each object, or might even mean using instanceof to distinguish different subclasses of ReportElement from one another.
Note that inspecting ReportElement objects like this violates the philosophy of object-oriented programming. A simple "object-oriented" solution would require all of your ReportElement objects to have a buildView() or getView() method, and so your GUI code could just call getView() on every ReportElement without knowing which implementation of getView() was actually being called.
Unfortunately, the object-oriented solution forces you to mix your view code with your model code, and it's good that you are trying to keep the two separate. That's why I would advocate keeping the GUI-building code out of ReportElement objects and instead using a factory method to build the right view for any given ReportElement.