I'm wondering should i use Singleton for my presenters?
What is the benefit of it?
I have a weird behavior in my simple project, i have a form which is used to add new records in db and display in a table, so after the first add "click" it works ok, but in the next second or third "click" then it comes weird. For example on the second click the event is called twice and the input is inserted twice in db, if you do third click the input will be inserted three time in db, why this happen?
Thanks
Edit
So far my presenters and views are Singleton , also EventBus and PlaceManager.
Implementing presenters as a singletons can reduce testability of your code.
Consider using a Dependency Injection. Gin works perfectly with GWT apps.
totaly difficult to answer that without seeing the code, maybe you can post the methods which are called after pressing the button?
Related
I am designing a android user interface for a sports app.
One of the features of the app is that the text of buttons and menu items changes as
the game state progresses. So you go from setup game -> start first half -> half time -> second half -> game over etc. The buttons and the menu item text change to indicate the next valid actions in the app.
Now so far I am doing that by watching a global var of the state and basically checking this in the various onCreate, onResume methods. at least for the buttons anyway. Not sure about menu items and how to make them dynamic.
Now I figure there must be a better way to do this in android ? In swing you might have a modelchangelistener and you could register as a listener of that in your view. Does something similar exist in android ? Also I know in Java you can do the Observer pattern but I was looking for something built into android. I imagine this scenario is fairly common.
But if there is not then NO YOU HAVE TO DO IT YOURSELF is an acceptable response to my question too.
Thanks in advance.
Frank.
Android does not have anything in particular like an Observer/Observable - even though you are free to use those in Android as well.
The question is: should you use Observer/Observable-classes, or not? Some say no, because it requires you to override an update-method which takes an Object parameter. This is not OO-friendly. Others, love it.
Those against it, suggest you write your own Observer classes, and register those Observers manually. Each Observable should then iterate through a list of Observer instances to say:
"Hey! Here's an update."
Good question.
You have to implement your own Listener and then you can use a selector in the XML file you create later on. Just like when you use it with Buttons : android:state_pressed="true"
Edit: However, I really suggest you don't spend time at all on this task as that can be accomplished in any other simpler way.
I have multiple places where I convert between one coordinate system and another. In each case there is a cosine/sine calculation between, let's call them x, y and x', y'. These are all JFormattedTextFields.
If the user enters a value in any of the 4, an ActionListener is called. Lets call the fields fieldx, fieldy, fieldx1, and fieldy1. If the user enters anything in fieldx or fieldy, I HAD keyboard and focus listeners (the same one for all four fields) that would update fieldx1 and fieldy1 from the current values in fieldx and fieldy. If the call to the listener was from fieldx1 or fieldy1 it would calculate fieldx and fieldy.
Then I decided to save fields chosen (including a bunch of check-boxes on/off and some spinners' values) in a config file (new requirement after development). I thought that by setting values and states all would be fine BUT certain things were not happening (behind the scenes). I decided that part of this is that the triggered methods by various checking and entering and etc were not happening because the fields did not trigger keyboard and focus listeners when they were set by a piece of code.
After reading online I changed all the KeyboardAdapter to ActionListener and after I set the value I call postActionEvent() on the fields I mentioned above and now all the background stuff happens (though order is an issue and I'm going to save extra information about state to update this properly). I made this change because I thought it would be more difficult to fire off so many fake keyboard events?
There are probably more clever/smart ways to do this but for now I'm trying not to touch too much code.
Does anyone have a suggestion on a way to save the state of a panel and refresh this (the current object, the panel)?
If I continue to do it in this way, can someone suggest a way to MINIMIZE the times the ActionListener fires? It seems to fire so often it is ridiculous!
Should I instead do things as suggested here?
Should your class implement ActionListener or use an object of an anonymous ActionListener class
That seems like a lot more coding involved but a lot more precise in what triggers when...
If this kind of question/discussion is out of place here, just let me know :). Just typing up this page has made me think of more things to read up on and to try.
I'm trying not to touch too much code.
This is a foundational mistake; the trash can is an important design tool, and one or more minimal examples will be invaluable in learning to compose more complex applications.
Does anyone have a suggestion on a way to save the state of a panel and refresh this (the current object, the panel)?
Using the Model–View–Controller pattern, the program's data should be stored in a suitable model, and transformations should be done when model elements are rendered in the view; the Converter example shows how to manage custom events, and this example expands on the topic
If I continue to do it in this way, can someone suggest a way to MINIMIZE the times the ActionListener fires?
As suggested in the original article, use Action to encapsulate behavior. See Java SE Application Design With MVC: Issues With Application Design for a deeper examination of the problem.
Is there any method to be followed before writing code for a GUI program? For previous programs, i had algorithm and/or class diagrams before writing code for the normal programs(those done before learning GUI)Should we follow anything similar while making GUI?I just made a small game(Book cricket) which involves using data stored in files and some computations.
I have completed the game just by making one thing at a time and so, i have lots of code. I just wanted to know if there is any procedure while making GUI based applications that can be followed for optimizing and making the code easy to read and debug?
To be more specific:
1. Should we design all panels in different classes?
2. If there are actionListeners for the objects, then should i put them along with the creation of the objects?
3. While using cardLayout to manage which panel should be visible, i often had to convert all the fields related to a panel static so that i could modify fields in one panel on actionEvents in some other panel.
Is this a standard thing to do or should i be doing something different.
4. I use the terminal to write my codes. Since i have just started working on GUI, i thought working with terminal would be a more better learning experience.Should i continue using terminal or switch to some IDE like eclipse/netBeans ???
Thanks
What kind of program does you want to write : it is a game or just an application ? For each kind of thing, often, there are patterns to do this. Moreover, for each kind of game or application, there are many ways to build framework. In other word, it's diversity, and depend well on program.
Nevertheless, in general way, there are some suggestion when you start to design your program. For example, you can apply MVC (Model-View-Controller) to this by :
View : this is a GUI and just a GUI. it contains code to build a GUI, build action listener for some objects such as buttons .... when some action appears on this GUI, for example, someone click a button, it will call appropriate action in Controller. So, View, in fact, doesn't really understand anything. It doesn't know (and doesn't care) this button or that button should do what.
Controller : connect between View and model. It will initialize View and Model. It will receive action from View, and call appropriate method from model and return result again to view. Controller knows how to control flow of data from user.
Model : a class with bunch of action that your application can do. Model doesn't really know, how to operate your program, it just holds the state of program.
Hope this help :)
My Java application is not very big, but I would like to do it the "right way". Looking for suggestions to not make a big mess...
I am using Swing, the Swing Application Framework and H2 database.
It is a single frame application with different tabs. Most tabs will reflect some aspects of the data in the database. Some of them will be able to change it. Some tabs will have buttons or actions that will redirect to another tab... that's basically it.
I would like to keep things clean, rather portable and flexible (can enable disable some tabs for example or add some easily).
Here are the questions :
1) How to have tabs "refreshed" when the database content changes ? Implement some Listener interface ? Should I define that interface or there is something already existing I can reuse ?
2) How to "link" the different tabs together so that it is easy to jump from one to another (and may have to carry some argument to setup the destination tab to the right "view")
3) If I set some preference with some filters in another part of the application, how do I share such settings with the whole application ?
And when I ask "how to", I really mean "what is the best way"... I can get that working already... just looking for the right tool to use, design pattern or such.
There are different strategies of gui application building. Here some article about.
If using swing, you can use tabbed pane to have a tabular layout.
Implement a listener (as you are planning). Have a look at observable interface in Java.
You can implement a singleton(eg PreferenceManager class) to hold the preference and access it across the application to access properties.
Do you really want a push model where the server has to maintain a connection to every client and then update them all when anything changes? This is feasible with a handful of clients, but quickly becomes problematic. It's probably better to use a pull model, where the client manually (periodically?) asks for updates. This is also a good way to use optimistic locking with a last_modified field in the DB. Attempt an update, if it's changed since you last reloaded, warn the user and allow them to overwrite / merge.
As for Swing in general, best practice is to factor everything out that's not GUI related into core classes ('business logic') that fire off events. Register all your Swing classes as the appropriate event listener and update the gui appropriately (SwingUtilities.invokeLater() is your friend here).
i've started on some basic java coding with gwt, and im getting a bit concerned about the heft of my main class.
For instance - how does one compartmentalize the keyhandlers, since they trigger a number of changes to the UI, how could i move this into a separate .class file and still be able to access all the various widgets in the main class, without having to pass everything to the handler (ie. all the widgets i manipulate after the click event).
i've googled but didnt come across any particularly good examples - know of any readily legible code-bases i could read to see how it should be done? (gwt's own tuts are pretty basic, and just kitchen-sink every thing into a single file)
thanks!
I hate to say something so unimaginative, but MVC works--it's not the ultimate, but it can start getting you organized.
EDIT: While searching on a semi-related topic, I came across this which has similar ideas to mine but goes into more detail.
What that means in terms of GWT is that you should think of just laying out your GUI components in one class, put all your event handling in a second and put your object model objects separate from the other two.
One way to accomplish this is to make most or all the controls on your GUI public members. This sounds kind of lame, but their usage is encapsulated inside the controller so it's not like you have uncontrollable access--in fact your access is clearer/better defined than if all your members were private but your view code was combined with the controller.
Specific tricks:
Have listeners be their own class. You can often reuse them-- in other words, avoid anonymous inner classes. I sometimes create a listener class and instantiate a new instance for each button/control that needs to have a similar effect when pressed. If I need it to act slightly differently for a given button, I'll pass something into the constructor of the "special" handlers so that they know to act a little differently. You can also create different handler sub-classes if necessary--I'm just saying don't forget that event handlers are classes, you can use inheritance and everything if need be.
One Very Old GUI Trick I learned a long time ago, try not to have various mini-handlers modifying the GUI in different ways, instead have all the "active" buttons and controls set a state within your GUI and then call a single method that applies that state to ALL the controls on your GUI. When you get beyond a trivial GUI this can be a life-saver. If I'm not being clear, leave a comment and I'll leave an example for you.
Property sheets:
There is a special case for GUIs--the property sheet style GUI. I've done a LOT of these and they are irritating as HELL. They tend to have dozens or hundreds of controls on them, each GUI control tends to be tied to a specific field in your model and there are just hundreds of lines of copy and paste boilerplate code connecting them, each group copied and pasted with a few items changed--at minimum it's like 3 lines of code per control (Create control, copy value in and copy value out).
I always write these with a "Smart" controller--one that can intelligently bind the control to some data without any unique code. This can get tricky and if this is your problem let me know in the comments and I can give you some general advice as to some tricks you might try. I've gone from a minimal reflective solution to a full-on XML based solution. Were I to do it again, I might consider annotation-based.
Example of MVC:
Note, this is just an example, there are a MILLION ways to do MVC.
In your MAIN:
Instantiate MyView
Instantiate MyModel
Instantiate MyController(myView, myModel)
myView.setVisible(true)
in MyView
probably extends Frame
Most components are public final (public final Button b=new Button())
If public members make you nervous, use getters--same EXACT effect as public final members with a little extra syntax.
Remember that you can set final members in your constructor.
May have general methods such as reset(), but MyController may be a better place for this.
in MyController
saves references to myView and myModel
adds listeners to myView where necessary (see advice on listeners above)
configures myView based on state of myModel
when "done" button pressed, copies state from myView to myModel
notifies myModel that it's data has been updated and destroys itself.
in MyModel:
This would be a typical model class, it would contain your business logic (mostly not used as part of the GUI, that's more like GUI logic in MyController. The controller would tend to set values in your business logic then call some method like updated() to cause some business logic to take control. It should know nothing of a GUI--this is your "pure" business class.
Sometimes the GUI might call an update() or some other method to trigger some data change and then reload the GUI controls from the Model--this is a fairly good way to integrate your business logic with your GUI without your model knowing about the GUI...
Also, as I said above, I would put more work into MyController if I was working with property sheets just due to the sheer number of lines of boilerplate that you end up with if you aren't smart about it.
Note that View and Controller are nearly always paired. You can't just replace a Swing view with a web view and expect the controller to remain unmolested--but the model should not ever change for the view or controller.
You should take a look at the best practices for GWT applications first:
http://code.google.com/events/io/2009/sessions/GoogleWebToolkitBestPractices.html
One of the concepts they talk about is that of MVP (not MVC) to structure your application. There's a sample project on Google Code that you can look at to understand how to structure a GWT application in this way:
http://code.google.com/p/gwt-mvp/