views:

48

answers:

2

This is basically a architectural question.

I want to implement composite pattern in handling Swing components; that is, I want to combine several components with their listeners and logic behind a single component for easier handling.

Consider for example a simple directory browser; say, a JTree in JScrollPane with some logic which handles populating filenames as user expands JTree nodes. How would you implement that?

Do you extend JScrollPane and add JTree and so on in constructor, and then your application deals with JScrollPaneExtended class? Or do you extend, say, JPanel or JComponent? Or do you stitch all those classes together in a method you call when you're populating your JFrame? Or something else? And why?

I'm basically looking for a rough guideline on what others use; I'd obviously like to deal with some form of JComponent for easier handling in constructing GUI, however somehow it doesn't feel right to extend topmost component (JScrollPane in this example) just to have someplace to put glue code.

+2  A: 

If you don't need a UI delegate, extending JComponent is fine; if you do, How to Write a Custom Swing Component is a good start. In the particular case of a tree-table, you might want to look at org.netbeans.swing.outline, as discussed in this answer.

trashgod
+1  A: 

I did exactly that for a proprietary swing app using a separate and parallel class hierarchy, with one "component" class wrapping one or several JComponents. I need a base class to do lots of common stuff (e.g. setting properties from an XML file) so extending JComponent is not an option.

For simple widgets like text field and button, my component class simply contains one widget. For anything that may scroll (table, list, panel), my component has a JSrollPane on top of the functional widget. I also have a "group" component that deals with a group of check boxes or radio buttons.

It takes some efforts to set up, but once you have the basic facilities, it's very easy to add new widgets.

Geoffrey Zheng
If you're not extending JComponent, what do you extend (or not)? How do you put your component in the GUI if it's not JComponent?
Domchi
@Domchi: My "component" is just a fancy wrapper around at least one concrete `JComponent` instance. The base class defines `JComponent getWidget()` (actually I genericize it with `<T extends JComponent>`), and the layout manager and everything else work just the same.
Geoffrey Zheng