Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Swing and MVC design

 
Barry Brashear
Ranch Hand
Posts: 303
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Would swing applications have classes called "controllers"? I've heard
that swing version of mvc is more a model delegate.

Thanks.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49789
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not sure about model delegates, but you do have control classes in Swing. You just call them ActionListeners or other Listeners.

If you have the ubiqitous calculator app you would have:
JFrame (V) with a Layout (V).
JButtons (V) for numbers +-*/ etc, with ActionListeners (C) registered to them.
JTextField (V) for result.
Calculating class (M) which does the work.
Some sort of class with main method to start it all off (M).

Was that of any help?

CR
 
James Ridley
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Barry Brashear:
Would swing applications have classes called "controllers"? I've heard
that swing version of mvc is more a model delegate.

Thanks.


You could consider the core JFC componets of Swing as delegates as they are both the controller and the view. Take a JTextField as an example. It is used to display the information from the Document it is bound to, but also updates the document as the user enters data into the field.

HTH,
James
 
Hari Surendran
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I feel the Swing framework itself is built on MVC framework and hence there, without doubt, are controllers. A view object such as Jtree has a corresponding TreeModel. But the controller code typically, in such cases, is part of the view class itself.

However if we are talking about a serious UI application, you must consider the MVC pattern with separate Model, View and Controller classes. A view object will be a java class that extend a JPanel(of course with other jpanels and text boxes, Combo boxes etc embedded). The model will be a java class with variables(to hold model data) and their getters and setters. The controller will be a third java class that will have various listeners etc that will have the controller logic. The controller logic could include state management, keeping the data in sync between view objects and model etc in addition to the classic controller job of listening to the user interaction and handling the user interaction logic.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic