please be advised, this is a long post. Sorry for that but I want to make my point clear:
I was wondering how to separate Swing GUI from Presentation and Business Logic for quite a long time. At work I had to implement a 3 MD Excel Export for some data with a small Swing Dialog to configure the export. We do not use a framework like Spring for this so I had to implement it myself.
I wanted to completely separate GUI from Business Logic, which are in precise following tasks:
- Tell BL to start its job from GUI
- Report Progress from BL to GUI
- Report Logging from BL to GUI
- Delegate BL Result to GUI
of course the GUI shouldnt have notice of the BL implementation and vice versa.
I created several interfaces for all those tasks above, e. g. a ProgressListener
, LogMessageListener
, JobDoneListener
,
etc., to be fired by the Business Logic. For instance, if the Business Logic wants to tell about logging, it calls
fireLogListeners("Job has been started");
classes that implement the public interface LogListener + are attached to the BL, now will be notified about the "Job has been started" log message. All these listeners are at this time implemented by the GUI itself, which in general looks like this:
public class ExportDialog extends JDialog implements ProgressListener, LogListener, JobFinishedListener, ErrorListener {
@Override
public void jobFinished(Object result){
// Create Save File dialog and save exported Data to file.
}
@Override
public void reportProgress(int steps){
progressBar.setValue(progressBar.getValue()+steps);
}
@Override
public void errorOccured(Exception ex, String additionalMessage){
ExceptionDialog dialog = new ExceptionDialog(additionalMessage, ex);
dialog.open();
}
// etc.
}
The "GUI and BL creating class" simply attaches the GUI (as all these listeners' interface) to the BL, which looks something like this:
exportJob.addProgressListener(uiDialog);
exportJob.addLogListener(uiDialog);
exportJob.addJobFinishedListener(uiDialog);
exportJob.start();
I am now quite unsure about that because it looks weird because of all those newly created listener Interfaces. What do you think about? How do you separate your Swing GUI components from BL?
Edit: For better demonstrating purpose I created a Demo workspace in eclipse file-upload.net/download-9065013/exampleWorkspace.zip.html I pasted it to pastebin also, but better import those classes in eclipse, pretty a lot of code http://pastebin.com/LR51UmMp