Hi All,
I am new to JavaRanch(great site!) and here comes my first question (or should I say discussion,
it has become larger then intended).
"How does the controller get data from his view."
In my opinion there are (at least) 4 possibilities.
1. The view knows his controller very well (this means the view has a "strong" reference to the controller).Controller has no idea about the view.
There are no special ViewEvents.View implements ActionListener, ListSelectionListener etc. (or maybe some inner classes do so) and then calls some controller-methods in actionPerformed(), valueChanged()...
Here the controller gets the required data as method-parameters.
2. The view knows his controller not so good (means view has a "weak" Reference to the controller).
Controller has still no idea about the view.
The controller would have to implement an interface (lets say ViewListener) which contains a method like
viewChanged(ViewEvent e). In this szenario view translates low-level Swing-Events to application specific events,
and the implementation of the above method would look something like the following
<code>
public void viewChanged(ViewEvent e) {
String type = e.getType();
Object data = e.getData();
if(type.equals(ViewEvent.BOOK_FLIGHT)) {
//cast data to something specific and call a method
}
else if (type.equals(ViewEvent.SEARCH_FLIGHT)) {
//and so on
}
.
.
}
</code>
The required data is transfered via the event-object which serves as an identifier and data-container. What I don't like on this approach are the if-else-if-....Furthermore , if I see a method where the parameter will be immediately casted to a specific type, in order to be usefull,
i have the strong feeling that there must be something wrong. The above code does not decouple
view and controller as much as it seems.
3. The view does not know his controller at all. But the controller knows his view very well. Controller (or inner classes) implements the required Swing-Listeners. The view provides
setter and getter for its controlls and nothing more. So in case of an ActionEvent the controller can do
something like
<code>
view.getBookingButton().addActionListener(new BookingListener());
view.getOriginTextField().getText();
view.getFlightsTable().getSelectedRow();
</code>
This looks ugly, because if I decide to change something in the view (like using Comboboxes instead of TextFields) I must also change the controller. Which leads directly to the last posibility.
4. The same like 3. but the view provides no setter and getters but rather some methods like
<code>
void addBookingListener(new BookingListener());
String getOrigin();
int getSelectedFlight();
<code>
I think that Mark would favour this.
(It is maybe not a bad idea to extract this all to an interface and let the view implements this interface?!)
Well, rangers what do you think. Which way did you choose and why?. Which way is preferable for building really large GUI's?
Any thoughts highly appreciated.
Reinhold