views:

169

answers:

3

If I have Swing GUI class and application, how should I manage communication between these objects? Should I pass GUI object link to app or app link to GUI?

Example:

public class App{

public App() { GUI gui = new GUI(this) }

}

or

public GUI{ public GUI() { App gui = new App(this) } }

+2  A: 

Have a look at the MVC pattern. Ideally you want to present your application such that different GUI components can make use of it (imagine later providing a web/servlet view of your application, or a command-line interface). That requirement prohibits your application having implicit Swing knowledge.

Brian Agnew
Note that in this case, it's OK to implement the view and controller in the same object (as in solution 2 of the OP). The separation between view and controller is only well defined in web applications where the browser is the view.
Wim Coenen
There's nothing special about web applications wrt. MVC
Brian Agnew
The only difference is that Java non-web clients(e.g. Swing/AWT) _can_ use MVC if so desired, but historically and realistically the Web apps _have_ to use MVC to be viable solutions.
Wintermute
A: 

Yes the MVC pattern will help. You really want to remove the tight coupling between the two components. Or at the VERY least, go with the latter, meaning:

public GUI {
    public GUI() {
         App gui = new App(this)
    }
}

That way, atleast your application logic doesn't rely on, or is bound to, you GUI.

Clinton
+1  A: 

The current answers are all good, but there is one very key thing here: You have the "Multithreaded" tag but no one has addressed it yet. You definately want to think about the "C" in MVC as something that will be threaded and might even want to follow the Manager Design Pattern via a Manager Interface and maybe even a View Interface--the use of Interfaces will help widen your options even more for future refactoring, or even redesigns. In the past I have used java.util.observer and java.util.observable--the original MVC Pattern ever in Java :)-- to cope with communication issues. Just remember not to block your main Thread or your GUI will freeze. Yes MVC is a good start but in the App->GUI you describe there is a bit more than just MVC, Think of the entire GUI as a View for your app, Model will more than likely be some kind of Dataset(DataBase, flatfile, state information) and the Controller your app. Keep in mind the GUI more than likely will at the very least have an Interface to it.

Wintermute