I am making a simple notepad application in Java and trying to use a fluid and immutable style, for the sake of trying it out. I have found it a lot of fun and am seeing lots of the great advantages that get talked about in regards to functional programming (code clarity etc.).
But I have an issue with event handling in general. I have one class TextArea that provides a Notepad-like document like you'd expect. Then I have another class ScrollBar . They are manipulated by a master class CentralController that keeps the scroll bar and text area working together (not the real class name, it's just for this example).
So if the user presses the down arrow, CentralController simply calls TextArea.withDownArrow() and that returns a new copy of the TextArea with the cursor moved down. The problem is the Scroll Bar now needs to be moved, so the CentralController needs to know whether the TextArea got scrolled by that down arrow.
My first attempt to solve it was to return an object that contained not only the new TextArea, but also a flag saying whether the scroll needs updating. That worked well but didn't feel right because I was no longer returning the TextArea whereas you really should in 'proper' functional programming (roughly speaking).
So then I tried having a flag inside TextArea that would get set if TextArea.withDownArrow() caused scrolling. That also works well but seems wrong to have a method result stored 'globally' in the class. It also has issues where you might call withDownArrow() twice and then the flag gets overwritten with a new result.
I have read a bit about Reactive Programming and it does seem interesting, but I'm not sure of it's suitable for this situation where you have a 'child' class sending a message to a sibling.
Just to add, I am under the impression normal event handling won't work in this situation. With immutable objects when you change something you create a new object. So any objects that try to send an event to a listener will be sending to an old pointer.
Am I missing an obvious way to do this because I feel like I am? Or is it actually ok to use normal Java event handling techniques and I'm worried about nothing?
Edit: I think I have worked out a good enough solution now. Even though the class that receives events (ScrollBar) is recreated all the time, the members of that class do not get recreated. Only things that change.
So I will just have an simple event receiver method in ScrollBar, and TextArea can have a list of listeners (basically the 'normal' way of doing events with listeners).
In summary my error was thinking I needed to send an event to a instance, rather than a member of that instance.
You have to differentiate between value objects and logic objects. Value objects contain nothing but values, no logic(*). They can be immutable.
But of course a text area cannot be a value object, nor can a scrollbar be a value object, because they must contain logic. Nor can they be immutable, because they contain state. So, scratch all that. It won't work.
(*) Or at least no logic that deals with external entities, or manipulates any of their own state.
Related
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.
I am using Sencha's GXT 3.0 to render a ListViewCustomAppearance with a custom render defined through XTemplate (html/css). It works well when things are read only or when the interaction occurs on the list-level (ie. item select, item deselect).
How do I add mouse events to elements defined in the template's markup? My end goal is to have a clickable element inside an item in the list. The event handler would be in java.
Please let me know if this is going about it the wrong way..
ListViewCustomAppearance is useful when you want to completely restructure the child dom, not just how each child gets drawn. By making one of these, you are taking over responsibility of deciding how to handle selection (see the com.sencha.gxt.widget.core.client.ListViewCustomAppearance.onSelect(XElement, boolean) method).
This is important because ListView already knows how to manage selection! You can set and configure a ListViewSelectionModel on the ListView itself to handle a variety of interactions, and can listen there for events.
Instead, consider just making a custom Cell (probably starting from the AbstractCell class) that renders your data how you want it to look. Override the render method to specify how to append new content.
One more tip - the ListViewSelectionModel idea may not work for you, depending on what kind of data you are trying to get about user interaction. Instead, consider also overriding the onBrowserEvent method - this gives you the model object of the item that was modified, a reference to the root of the rendered content (from your render method), and the event itself. Use the event object to see what happened (test the event.getType() against a string event type). When subclassing AbstractCell, you also need to pass the event you are interested in to the superclass constructor.
Check out ActionCell as a pretty good example of how to rough this out. It is designed to be abstract enough to be reusable, but that also tends to make it a poorer example.
I am having issues understanding which interface I need to listen to changes in a listModel. I thought it was ListDataListener, but I can't understand the methods in it. There are 3 methods in it and this one seems to be the one I want but I can't understand the description:
contentsChanged(ListDataEvent e)
Sent when the contents of the list has changed in a way that's too complex to characterize with the previous methods.
What does it mean by "too complex"? And by "characterize with the previous methods"? Well, what does the whole thing mean? Is this the interface I want?
ListModel dispatches events to its ListDataListener listeners. It's more efficient for the list model to invoke the detailed intervalAdded and intervalRemoved methods when possible. The Listener of the list model (in this case a JList) can use these detailed changes to make minimal changes to the visual component (ie, for intervalAdded it can just add the new row instead of redrawing the whole list).
However, some changes may be too complex to be described as with just added and removed. In this case, the list model has the option of invoking contentsChanged. When JList sees contentsChanged it will most likely refetch the entire list from the list model.
Yes, that's the right listener.
The statement means that this method is the more general one, that will cover every possible change to the list content. The other ones (intervalAdded and intervalRemoved) should be used when those specific events occur.
In my practice you will always use the most general one (even with table listeners).. I guess it was supposed to be used to optimize (especially with big lists).
A tutorial on this listener can be found 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/
As described in another question, I have a set of Model objects and an associated set of Panel objects which allow the user to access the data in the Model objects. The Panels are registered as PropertyChangeListeners for the Models, such that if something else updates a value in a Model, it fires a PropertyChangeEvent, and the Panel receives it and knows to resync its values from the Model. (Currently I'm naively just updating all the values, but this could be made more intelligent to pull only the changed property.)
All of this makes sense when a Model is updated by some arbitrary, unknown source, which does happen in my application. However, most often a Model's properties are set by the Panels themselves. In this case, now that I've hooked the Panels up as PropertyChangeListeners for the Models, my code is doing something that makes no sense: after the Panel updates the Model, the Panel receives a PropertyChangeEvent from the Model and pulls the same value from the Model that it originally sent to the Model in the first place. No update needs to occur, and it makes no design sense for this to happen.
So how do I register something as a PropertyChangeListener but then say "Don't notify me of PropertyChangeEvents when I am the source of them?" (Note that I can't answer this by calling PropertyChangeEvent.getSource(); it'll give me my Model, not the Panel that sent the value in the first place; there's no way to look at this and tell what changed the Property.)
In all reality, do you really care if you get that event fired back at you? It allows you to handle any times the Model is changed outside the Panel and there really isn't a lot of overhead involved in checking to see if you actually have to update the value.
The PropertyChangeEvent holds the property being changed as well as the old and new values. You can check each incoming event to see if the value in the Panel is the same as the new value, and if it is then discard that event. The Model should tell everyone that is listening to it for PropertyChangeEvents every time it has changed otherwise it will need to know too much about the Objects that are listening to it.
Whatever you do, DO NOT create property change event listener loops. You will end up with a situation that very easily can end in an infinite loop if you are not very careful.
I don't think that there is any measurable detriment by the unneccessary repaint during runtime. So from that point of view there's no need of changing the code. In that situation you should decide having regard to design/architecture. You say:
...and it makes no design sense for this to happen...
, but it does!
If you want to avoid the repaint, you have to add the source (the panel) to the parameters of the method(s) that change(s) the model, put it into the change event and consider that parameter when evaluating the event again, which makes your code much more complicated. Think what else you have to do, if there are two instances of the same panel, one that changes the model, one that has to be changed after receiving the event...adding object-ids to method calls...What if later changing the design of model or view the way that editing one field of the panel leads to changes of the model that are shown in another part of the panel - additional changes again...etc.
Moreover, if you would do as described, you'll break with the decoupling of model and view, which is never a good idea.
If you want to keep it simple, leave it as it is. The only reason to write complicated code is bad results during runtime and I don't think you'll get that.