Design for separating code and GUI - java

I need to create a Playlist, I want to separate code/logic and GUI by using two classes:
Playlist (code/logic)
PlaylistGui (GUI)
It shall be possible to use the Playlist class standalone, e.g. in some kind of command line environment. The question now is, how would one plug both classes together, when using a GUI? My ideas until now:
Expose an observable list from the Playlist class, create a method setItemSource(Playlist source) on the PlaylistGui class
Not sure if possible in Java, just know this from .NET: Let Playlist class fire events and let PlaylistGui catch them, should lead to uncoupled code? :-)
Open for new ideas :-) Note I am using Java 7 and JavaFX, though I guess JavaFX doesn't limit possiblities, just extends them.

Events in Java:
http://castever.wordpress.com/2008/07/31/how-to-create-your-own-events-in-java/
Other alternatives are:
Java Delegates?
or both as separate processes with communication via sockets

Have a look at FXML, Controllers and the SceneBuilder tool.

I think your basic concept is sound, delegation of responsibility.
I would create an interface of the model, exposing only those methods you think that any basic controller/viewer would want. This means you can change the implementation without effecting any of the components that rely on it.
Listeners are, essentially, just a call back mechanism, where interested parties register themselves (through a common interface) to be notified when something occurs that they are interested.
Take a look at Writing Event Listeners for more information.
I would basic start out with a common library which defines the basic interfaces that all parties would need to know out (such as the PlayList and listeners).
This would allow to design 'n' implementations of the playlist based on your needs

Related

Why do we need interfaces to achieve event listeners in java?

I have this doubt in Java: when people are writing an event listener they implement an interface and they define a particular function in the interface to achieve a particular task. My doubt is instead of implementing an interface can we just define the function with the an appropriate name.
Also, how interfaces help in achieving event listeners?
Because many different classes would want to listen to the same event and Java does not allow multiple inheritance.
The Listener interface gives you a lot a implementation freedom.
This way you don't have to implement a specific function in a specific class. Though implementing an interface seemes to be the same, it isn't. The functionality of a listener is just still ja single function, but the function is usualy in a lightweight object. Yet you are able to implement a lot of program mechanics inside a listener, if you need to.
Also, you can change the listeners at runtime. You can't change an overriden function.
There are a lot of good reasons to use composition (over inheritance) here.
If you really want to understand this, I encourage you to look inside "Heads first: Design Patterns". The "look inside" feature of amazon contains the complete chapter 1, which explains this pattern greatly.

android object oriented programming

I am fooling around with some basic programming in Android using Eclipse. I'm currently looking through a book and playing with some sample code that is written in the book.
I have noticed that in this particular book, all of the examples so far take pace in Main-Activity. I don't believe this to be very good Object Oriented programming practice as I am from a traditional Java background.
Is this the common practice for mobile platforms? Shouldn't classes all be contained in their own files?
Shouldn't classes all be contained in their own files?
Not necessarily as an Android Activity is a 'special case' class. If you haven't done already, I'd recommend you read Application Fundamentals and in particular the section on 'Activities' under Application components...
An activity represents a single screen with a user interface. For example, an email application might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails. Although the activities work together to form a cohesive user experience in the email application, each one is independent of the others. As such, a different application can start any one of these activities (if the email application allows it). For example, a camera application can start the activity in the email application that composes new mail, in order for the user to share a picture.
Note the section of text that I've highlighted in bold. The point is that an Activity in itself is not the complete app and if allowed, any third-party app can potentially invoke an Activity in one of your apps. As such, it is common to make an Activity as self-contained as possible. One particular example is the use of something like an AsyncTask which provides methods to execute a background thread as well as manipulate the UI - nesting a private class which extends AsyncTask is quite common and simplifies code. Nesting classes which extend BroadcastReceiver is also common for the same reason.
That said, there is nothing wrong with using separate Java class files for POJO helper classes, for example, it just comes down to how complex your app is but it can mean taking special consideration of how certain Android classes work - the AsyncTask class being one in particular if defined in a separate class file, try it and you'll see what I mean. :-)
OO is about putting functionality in classes. The way you write those classes defines if it is good OO or not (although this is debatable). Whether all these classes are in a single or a few files, or each class has its own file, is a matter of taste and is not directly an OO issue.
Since this is a book with (I think) small samples, it may be just as easy to read the way it is, than when all classes are in separate files.
If you use proper OOP you can create Template based apps much more quickly & efficiently.
You should strive to do this for example if you have a generic database app and multiple databases can be used with minor changes.

Questions: controlling a Swing GUI from an external class and separating logic from user interface

UPDATE: I'm using Netbeans and Matise and it's possible that it could be Matise causing the problems I describe below.
UPDATE 2: Thanks to those who offered constructive suggestions. After rewriting the code without Matise's help, the answer offered by ignis worked as he described. I'm still not sure how the code the Netbeans code generator interfered.
Though I've been programming in Java for awhile I've never done any GUI programming until now. I would like to control a certain part of my program externally (updating a jTextArea field with output from an external source) without requiring any user action to trigger the display of this output in the jTextArea.
Specifically, I want this output to begin displaying on startup and to start and stop depending on external conditions that have nothing to do with the GUI or what the user is doing. From what I understand so far you can trigger such events through action listeners, but these action listeners assume they are listening for user activity. If I must use action listeners, is there a way to trick the GUI into thinking user interaction has happened or is there a more straightforward way to achieve what I want to do?
Also, I'd really like to know more about best practices for separating GUI code from the application logic. From the docs I've come across, it seems that GUI development demands more of a messy integration of logic and user interface than, say, a web application where one can achieve complete separation. I'd be very interested in any leads in this area.
There is no need to use listeners. GUI objects are just like any other objects in the program, so actually
you can use the listener pattern in any part of the program, even if it is unrelated to the GUI
you can invoke methods of objects of the GUI whenever you want during the program execution, even if you do not attach any listeners to the objects in the GUI.
The main "rule" you must follow is that every method invocation performed on objects of the GUI must be run on the AWT Event Dispatch Thread (yes, that's true for Swing also).
http://download.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html
So you must wrap code accessing the GUI objects, into either
javax.swing.SwingUtilities.invokeLater( new Runnable() { ... } )
or
javax.swing.SwingUtilities.invokeAndWait( new Runnable() { ... } )
http://download.oracle.com/javase/6/docs/api/javax/swing/SwingUtilities.html
About "separating GUI code from the application logic": google "MVC" or "model view controller". This is the "standard" way of separating these things. It consists in making the GUI code (the "view") just a "facade" for the contents (the "model"). Another part of the application (the "controller") creates and invokes the model and the view as needed (it "controls" program execution, or it should do that, so it is named "controller"), and connects them with each other.
http://download.oracle.com/javase/tutorial/uiswing/components/model.html
For example, a JFoo class in the javax.swing package, that defines a Swing component, acts as the view for one or more FooModel class or interface defined either under javax.swing or one of its subpackages. You program will be the "controller" which instantiates the view and an implementation of the model properly (which may be one of the default implementations found under those packages I mentioned, or a custom implementation defined among your custom packages in the program).
http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/package-summary.html
That's a really good question, IMHO... one I asked a couple of years ago on Sun's Java Forums (now basically defunct, thanx to Oracle, the half-witted pack of febrile fiscal fascists).
On the front of bringing order to kaos that is your typical "first cut" of an GUI, Google for Swing MVC. The first article I read on the topic was JavaWorld's "MVC meets Swing". I got lucky, because it explains the PROBLEMS as well as proposes sane solutions (with examples). Read through it, and google yourself for "extended reading" and hit us with any specific questions arrising from that.
On the "simulated user activity" front you've got nothing to worry about really... you need only observe your external conditions, say you detect that a local-file has been updated (for instance) and in turn "raise" a notification to registered listener(s)... the only difference being that in this case you're implementing both the "talker" and the "listener". Swings Listener interface may be re-used for the messaging (or not, at your distretion). Nothing tricky here.
"Raising" an "event" is totally straight forward. Basically you'd just invoke the "EventHappened" method on each of the listeners which is currently registered. The only tricky bit is dealing with "multithreaded-ness" innate to all non-trivial Swing apps... otherwise they'd run like three-legged-dogs, coz the EDT (google it) is constantly off doing everything, instead of just painting and message brokering (i.e. what it was designed for). (As said earlier by Ignis) The SwingUtilies class exposes a couple of handy invoke methods for "raising events" on the EDT.
There's nothing really special about Swing apps... Swing just has a pretty steep learning curve, that's all, especially multithreading... a topic which I had previously avoided like the plague, as "too complicated for a humble brain like mine". Needless to say that turned out to be a baseless fear. Even an old idiot like myself can understand it... it just takes longer, that's all.
Cheers. Keith.
This doesn't exactly answer your question, but you might be interested in using Netbeans for Java GUI development. You can use GUI in Netbeans to do Java GUI development.
Here's a good place to get started -
http://netbeans.org/kb/trails/matisse.html

Does Mediator Pattern work in this situation?

So for my current project, there are basically three main Java classes:
GUI
Instant Messaging
Computation
Essentially, there needs to be full communication, so we've decided to use the mediator approach rather than than allow the GUI to run the entire project.
Basically, the mediator is going to encapsulate the communication. The problem we've run into is how to allow the GUI components to update without building a ton of methods for the mediator to call anytime something completes.
Ex. Say the GUI wants to log in the user, it goes through the mediator to create a thread and log in, but then the mediator has to relay the success/failure back to GUI as well as update a status message.
The other issue is things that need to update the GUI but do not need the moderator. Is it practical to just allow the GUI to create an instance of that class and run it or should everything go through the mediator?
Our original design just had the GUI managing everything, but it really killed reusability. Is there a better design method to use in this case?
If you're finding Observer to bring too much overhead, Mediator may be the best way to go. I definitely think that you shouldn't have the GUI run the show. If you're going to use the Mediator pattern, the mediator itself should be in charge. Something you might consider is a variant of the Command pattern. If you were using Ruby, I might recommend passing function callbacks around as a means of avoiding having the mediator contact the GUI for every little thing. But since it's Java, some form of encapsulating an action in Command pattern style may help.
If you don't want the callback/notification to be triggerd by the mediator, you can inject the callback into the login function and have login call it when it finishes.
I don't know how you would go about injecting the callback in Java, though. In a language where functions are first class citizens, you could just pass the function, but you're in Java so I guess you will have to use the command pattern as kmorris suggested.
You might also try having the GUI give the mediator a callback object that handles retrieving return values or setting whatever values you need (a version of the Command pattern). There would then be one per call from the GUI to the mediator.
Another thought is to group the methods the mediator calls into semantically related chunks. In particular if the mediator has sections where it tends to call several GUI methods in a row:
gui.a()
gui.b()
gui.c()
you can create a single method that handles the result of calling all three. The advantage of semantically grouped methods (i.e. setFileInformation over setFileMenu, setTab, etc.) is also then if you need to change the GUI, the contents of the methods might change, but the call the mediator makes may not.

Java Events: Is this a good way to go about it?

I'm reimplementing a .Net API in Java and the API specifies a whole bunch of events, ehich java doesn't implicitly support.
I'm going to use an observer pattern but due to the number of event I really don't want to clutter the interface.
I was wondering if it was a good idea to declare an "Event" class which has a subscribe method which takes an "EventHandler Interface" and a throw method.
this way I'm not cluttering my parent class with umpteen lists of subscribers because the individual events handle them.
The only issue I can see is with the arguments for the throw command, as different events would have different arguments.
The solutions I've come up with are letting the throw method accept an array of objects or, creating an interface like IEventArguemnts which can be passed to the throw command and handled by the code that has subscribed to the event, this seems to make more sense to me.
I'd appreciate any suggestions for improving this. Or any refinements.
Java has events, and also API support for events. Check out the java.util package. You'll see java.util.EventListener, java.util.EventObject and some others. There are also support classes for maintaining subscribers, etc. The AWT and Swing APIs for example are heavily event-based.
Normally the addXxxListener(XxxListener l) methods (i.e. the subscription methods) would go on the class that's firing the events, not on the event class itself. The event is the message and it's what's being fired from publisher to subscriber.
Why not just use the JavaBeans event model? If all the objects are running in the same JVM, that will work fine.
Peter Coad had some thoughts about improving the Java Observer model. Perhaps you'll find these helpful.

Categories