Hey all, I'm currently working on a Java Swing application and I was looking for some guidence. The application is fairly small, but I'm noticing that as the code base is growing larger, that I have an awful lot of 开发者_开发技巧coupling in my object graph. I'm relatively new to Swing, but I've been programming long enough to know where this is headed.
The biggest problem I'm having is setting up my event handling. How should my child windows and objects be communicating events to my higher level objects without having references to them? I've done a fair amount of MVC web coding. Does this pattern lend itself well to Swing? Should I be building my own controller? I guess I'm just fishing for patterns that people have found useful working with Swing.
Thanks in advance for your help.
The best way to reduce coupling in a GUI, I think, is to use an Event Bus. There are several existing implementations out there, including some supporting Swing specifically.
Just google for swing event bus and you'll find.
If you use Guice in your GUI, you may also want to take a look at guts-events.
Yes. MVC is what you have to use. Here is a very good article about MVC and Swing:
http://java.sun.com/products/jfc/tsc/articles/architecture/
Another Pattern that might be interesting for you is the MVP (Model View Presenter)-Pattern. This is great for coupling views more loosely to the model. A good explanation by Todd Snyder can be found here.
As you already said your intent to use MVC , or you may be already using. Once you have seperated out data (I call it as data model layer). Now you need to apply OBSERVER pattern on these data model classes. All the views (your ui components) using this data model are observing this model objects for any change (Via observer pattern).
I hope this is what you are looking for.
MVC !!! Then you can use also a variant of Observer called Publish/Subscribe in order to implement the event flow inside your app.
I don't agree with the people who suggest to use Event bus, because
- because of code like
EventBus.subscribe(SymbolListChangeEvent.class, this);
your whole code will depend on a single event bus instance which makes it very hard to test, - it is hard to find out where a specific event is used.
Instead I suggest to use interfaces to encapsulate external dependencies of a module. If you like, you can use them with the listener pattern, but generally are free to refactor everything if you like.
If you want to communicate with other GUI components in the hierarchy then you should consider something like singleton that mediates calls between branches. See :
http://blue-walrus.com/2013/06/mediator-pattern-in-swing/
精彩评论