Let's say I'm building a Java Swing GUI, and I've got a frame which contains a panel, containing another panel, which contains a button. (Assume the panels are reusable, and so I've made them into individual classes.)
Frame → FirstPanel → SecondPanel → Button
In reality, the line of children could be more complex, but I just want to keep this example simple.
If I want the button to control one of its parent components (eg. resize the frame), what is the best way to implement functionality between two GUI classes that aren't necessarily one directly inside the other? I don't like the idea of stringing getParent() methods together, or of passing the instance of Frame down through its children so that it can be accessed from SecondPanel. Basically, I don't want to daisy-chain my classes together one way or another. Is this an instance in which the button should be updating a model and not the parent component directly? Then the parent is notified of the model's change and updates itself accordingly?
I've put together a little example that should compile and run on its own to illustrate my problem. This is two JButtons in a JPanel, in another JPanel, in a JFrame. The buttons control the size of the JFrame.
What I don't like, is that the controller needs to exist in the JFrame so that the frame can register itself to receive events. But the controller then has to be passed all the way down to the SecondPanel (lines 112, 131, and 143) so that the panel can communicate with the model. I feel like there is something inefficient going on here (and the classes become too tightly coupled). Let me know if my problem isn't clear.
Why do you consider the so-called "child-parent" relationship to be significant? There are many cases where one component's action can cause another component to change -- for example you might click on one button, causing an action which grays out a menu item. I don't see any reason to treat this sort of thing differently just because the actor happens to be a "child" of the target of the action.
Joined: Apr 15, 2011
I guess what my question boils down to is: Should I be trying to avoid situations in which ((JFrame)getParent().getParent().getParent()).setSize(...) is the way a child component accesses its parent? (That's why I specified the child-parent relationship.)
I just included the longer example to suggest MVC as a possible solution.
The most important element in a Model-View-Controller implementation is the Model. It is the business logic and the business data that are in the Model that matters most, not the View. The basis of the MVC pattern is to reduce the coupling between the Model and a particular View. Ideally, it should relatively easy to implement multiple Views for a single Model component.
The Model in a MVC implementation should not have knowledge of, or dependencies on anything View related. It should only communicate with Controllers.