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

mvc - adding views to main GUI frame

 
Jonathan Janisch
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi. I just read Head First Design Patterns (it's an awesome book!). In the chapter on MVC, it says the controller creates the view. This works great for their example, because their view is the main JFrame. In my case, my views are components I want to add to my existing JFrame.

I have the EXACT same problem as this guy and oddly enough he also just read the same book:

http://forum.java.sun.com/thread.jspa?forumID=425&threadID=5138897

but I don't necessarily understand the answer he was given.

So, since he's better at explaining it, I'm going to quote his post:


Hi,

If I have a a couple of different Views which are created by a couple of different controllers what would be the best way of adding these to a main frame.

For example

View1 extends JPanel
View1Controller creates it.

View2 extends JPanel
View2 Controller creates it.

MainFrame extends JFrame

currently I have the controllers returning the View that they create so I can add them like so


getContentPane().add(controller1.getView1());
getContentPane().add(controller2.getView2());



This however does not sit right with me, though I'm not sure why.

Does anybody have any thoughts or insights on the above.


In addition to his question, should my main JFrame be creating controller1 and controller2? Or should this be done in non-gui code and passed into the MainFrame constructor?

i.e.


or should I do this:



I believe the first approach is better as long as the MainFrame is allowed to create the controllers. With the second approach, if I have 10 controllers, these all have to be passed to the MainFrame constructor. Or are none of these approaches correct?

I'm open to any advice. I feel like I'm closer than ever to understanding MVC thanks to HFDP, so thanks if you were involved with that book.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49733
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Is this recent article from the Java Developers' Series any use to you?
 
Jonathan Janisch
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.

That did help. I'm not quite sure if I like their modified MVC approach, but I can use the part where they add the views to the controller.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49733
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic