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 lo开发者_如何学Gooking 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.
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.
I did exactly that for a proprietary swing app using a separate and parallel class hierarchy, with one "component" class wrapping one or several JComponent
s. 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.
精彩评论