A well-known and good practice is to avoid subclassing top-level containers ( JFrame , JDialog , JInternalFrame ).
Regarding JPanel , several methods are used:
- subclass for each view (then add all components inside the constructor subclass)
- create a ViewBuilder (for each view type) that dynamically adds components to the "standard"
JPanel
Usually I use the first option, which seems more logical to me, but I also sometimes use the second method with some level of adaptation: my view designer actually creates and saves (as fields) all the components, but adds them to the existing panel (passed as an argument).
For example, I use this to reuse sets of components: for example. I have an AddressView class that works this way and I add it twice to ContactView that subclasses JPanel , once for the home address, once for the business address.
You could say that I could also subclass JPanel for AddressView , and then add 2 instances to my ContactView panel. The reason why I do not do this is because Swing LayoutManager does not support alignment of components on different panels, so the resulting ContactView panel does not look visually pleasing in this case.
source share