Adding listeners at runtime? - Java MVC

My model in my MVC template generates components at run time and gives them a view that will be displayed on the screen using the update () method (you know, the model is observable and the view is an observer). But I also need to add listeners to these components, and the controller has listener methods (because they say that the MVC pattern is similar to this), and it is not involved in this update process. Therefore, I cannot add listeners at runtime, but only in the controller constructor at startup.

I have an idea that makes the controller an observer, and then gives the data for presentation, and also adds listeners. Do you think everything will be alright?

+3
source share
3 answers

Yup, having made the controller your model observer so that it can update the presentation, will finally fit, in my opinion, in MVC spelling.

+2
source

I think you can cross some wires.

  1. The model is observable (check!)
  2. The view is watching the model (check!)
  3. The controller is attached to the view (TODO!)

No. 3 means that user interactions from the view must call a registered listener in the controller class, which then updates the state of the model.

This is the "classic" Swing MVC. (source: sun.com )alt text

"" Swing MVC ( ), .

, . (, ). , , ( , ).

"" MVC. alt text
(: sun.com)

("" MVC) .

, Java Swing MVC. .

+3

In a swing, for example, the controller / action performer is an observer for the presentation (buttons, etc.) and when the buttons are called (i.e., when the view changes), the controller starts and interacts with the model and updates the view again (using new model changes )

So, what you suggested at the end makes sense to me :)

+2
source

Source: https://habr.com/ru/post/1737118/


All Articles