In the same window, I have 3 times the name of an item:
- in a JButton (a button allows to select one of the items)
- in a JLabel to show the selected item
- in a JTextField that allows to edit the name of the item
(I hope it is clear)
Perhaps I am wrong, but I guess I have to use a MVC design to
synchronize the text of all the component: when the TextField changes,
the text of JButton and JLabel changes; and when an item is seleted
(button clicked), the JLabel and TextField changes.
I tried to figure out how to implement it in a clean way using
Model/View/Controller in swing but I hardly know how to start.
I read the article at
http://java.sun.com/products/jfc/tsc/articles/architecture but there is
no example of how to define one's own model and view.
Can someone tell me if the use of MVC for my problem is a correct
analysis and if yes can someone point me to what should be defined
(interface, classes) to make this in a clean way ?
Thanks in advance.
Jacob - 06 Sep 2004 07:42 GMT
> In the same window, I have 3 times the name of an item:
>
[quoted text clipped - 7 lines]
> the text of JButton and JLabel changes; and when an item is seleted
> (button clicked), the JLabel and TextField changes.
You apply the MVC pattern as follows:
1. Have a private class variable that represent your current
selection.
2. Add a refresh() method to refresh the GUI components you
list, based on the private variable above
3. Make your window implement ActionListener. Add it as listener
to your button. In actionPerformed() update the internal
selection variable, and call refresh()
4. Make your window implement caretListener. Add it as
listener to your text field. In caretUpdate() update the
internal selection variable and call refresh().
The variable in (1) above is your model ("M"). The three GUI
components are your view ("V") as expected. The window class act
as the controller ("C") by the listeners and the refresh method.
That said: You might want to look at your GUI design. When you
encounter a situation where several GUI elements must be
synchronized like this you probably violate the principle of
unique representation of concepts. You make the classic error
of applying patterns to the wrong problem which is a well-known
"anti pattern".
See if you can replace the three GUI components with an
editable combo box.