MVC meets Swing

Explore the underpinnings of the JFC's Swing components

1 2 Page 2
Page 2 of 2

To build this applet, I created two subclasses of ButtonUI and two subclasses of ButtonModel. On the view/controller side, I created a plain-looking button and a fancy-looking button. You can choose between them using the first of the two combo boxes. On the model side, I created a momentary button and a toggle button. You can choose between them using the second of the two combo boxes. Download the complete source code from Resources too see exactly how I accomplished this.

You'll notice that both the model and the view/controller can change independently. This is where the MVC pattern really shines. You can create a new view/controller implementing a new look-and-feel and can use it without having to change the button model or the button user interface component. The same holds for the model. You don't even have to tell the other parts of the button that anything changed. Now that's flexibility!

Conclusion

I hope you were able to follow all of that. If not, all is not lost. The nice thing about this example and the Swing user interface components is that you don't have to understand the underpinnings in order to use them. They both provide sensible defaults for both model and view/controller. However, when you need it, the power is there!

Next month, I'll continue this heading as we take a look at the data transfer capabilities of Java.

Todd Sundsted has been writing programs since computers became available in convenient desktop models. Though originally interested in building distributed object applications in C++, Todd moved on to the Java programming language when it became the obvious choice for that sort of thing. In addition to writing, Todd is president of Etcee, which offers Java-centric training, mentoring, and consulting.

Learn more about this topic

  • The Swing Tutorial http://developer.javasoft.com/developer/onlineTraining/swing/
  • The JavaSoft Swing API http://www.javasoft.com/products/jfc/swingdoc-current/api/packages.html
  • The Swing Connection http://www.javasoft.com/products/jfc/swingdoc-current/
  • Download this article and the complete source as a gzipped tar file http://www.javaworld.com/javaworld/jw-04-1998/howto/jw-04-howto.tar.gz
  • Download this article and the complete source as a zip file http://www.javaworld.com/javaworld/jw-04-1998/howto/jw-04-howto.zip
  • Previous How-To Java articles

1 2 Page 2
Page 2 of 2