Java Swing: how to create a GUI and pass domain objects correctly?

I have a graphical interface with nested panels (tabs with nested panels, etc.). I need to transfer the domain object to a deeply nested panel. I can think of two ways:

  • Activate all gui objects in one place, for example, a frame class. Which will lead to the fact that the objects of the intermediate region will be simple, but the Frame class will be huge and hardly supported.

  • Each panel has its own class, where we create an instance and place its components. Now itโ€™s easy to maintain and the classes are clean, but how do I pass the chain of objects of my domain? I do not want to drive them through the panel designers, who should not even know their existence. And the top-level panels will have a ton of these objects to start with.

The thread looks like a soul. How do you usually understand this?

+6
source share
2 answers

When I compiled the Java Swing GUI, I have a data model for each core element of the GUI. Please note that this is not an MVC pattern. This is more like a local MV pattern. If you want, you can consider the listeners of the GUI elements as a โ€œcontrollerโ€.

Each panel has its own class, where we create and assemble its components. Now itโ€™s easy to maintain and the classes are clean, but how do I pass the chain of objects of my domain?

You have the right idea, although you do not need to go through much.

My JFrame (or JApplet ) will have an associated model class of global field types. An instance of this model class is usually passed along with children. This allows children's items to respond appropriately when selecting a menu option (as an example)

My JPanel(s) will have an associated model class that maintains the state of text or child elements.

More complex children, such as JList or JTree , already have an associated data model. I will probably be porting these related data models to the JPanel model class for convenience.

The children elements will cause some kind of choice or action listener. Some of these listeners may require access to model classes other than the model class associated with the parent. In this case, you will have to pass instances of your model classes to listeners.

+2
source

This is a kind of chain of responsibility chain. I would do what creates a map with all your display objects in it and passes it from constructor to constructor. Thus, each instance can take what it needs from the card without worrying about what else is there.

0
source

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


All Articles