I was looking for a way to sort data in a JTable today and I very soon came upon this section in Sun’s docs. TableSorter.java is so easy to use that all I had to do was literally this:
- press the new class button in Eclipse,
- choose javax.swing.table.AbstractTableModel as the superclass (parent),
- fill in TableSorter as the class name
- click Finish
- replace everything but the package statement at the top of the new java file with the contents of TableSorter.java
Voila. Took way longer to type this description than it did to actually do the work.
After that I changed the few lines of code as they describe. I ran it and tested it out, then I went back to figure out what I’d done. If you read the Sun documentation you’ll get a lot of what I did. I also had the GoF (Design Patterns: Elements of Reusable Object-Oriented Software) next to me though. So I looked up the Decorator Pattern.
To paraphrase (I don’t have it next to me now), the Decorator Pattern allows the developer to add functionality to a class without subclassing. Instead you write a sort of intermediary that exposes the same interface as the class you want to augment but with a couple extra features or methods.
Read the rest of “The Decorator Pattern and the JTable”…