I am creating a JList dynamically and I want to use it on different JPanels where I can call a setQuery(query); on it. There is a Search Button + field connected to it too. Is there a way to place the JList, search button and search field on like 10 different panels without having to duplicate the code everywhere? I can't place it on a seperate JPanel as it has other buttons / gui elements that need be around it depending on what JPanel is being displayed. I've looked everywhere but there is not much mention of reusing a dynamic JList.
-
Please provide one ASCII art or drawing that shows how the GUI should be laid out with one of the '10 different panels', and another to show how extra space is allocated (I.E. What stretches vertically? What stretches sideways?). – Andrew Thompson Apr 24 '12 at 18:14
2 Answers
You can place a component in one visualized container only. Consider creating a method that creates these components for you, that returns a JPanel that holds the components, and perhaps have all created JLists share the same ListModel, and all JButtons the same AbstractAction.
Or another option, if you are using CardLayout to swap JPanels, and you want all of the panels to hold these components above, consider not doing this but moving the JList, JButton, and JTextField out of the cards and on to a less dynamic portion of your GUI.
Also, this is not clear to me:
I can't place it on a seperate JPanel as it has other buttons / gui elements that need be around it depending on what JPanel is being displayed.
Please clarify and tell us more. Images might help as well.

- 283,665
- 25
- 256
- 373
Also consider the decorator pattern Your list/search panel would be the main component, while the variations would result from decorating the original.

- 203,806
- 29
- 246
- 1,045
-
1See also [*Examples of GoF Design Patterns*](http://stackoverflow.com/q/1673841/230513). – trashgod Apr 24 '12 at 23:49