Wowsers! Sun’s Updating The Swing Text APIs
By Adrian Sutton
Apparently Sun has finally decided to give some love to the Swing text APIs with the addition of a removeElement method. What the linked article fails to mention is that in the particular example given, you can remove the list item with a simple document.remove(e.getStartOffset(), e.getEndOffset() - e.getStartOffset());
When you get into trouble with the swing text apis is when there are two elements that start and end at the same point – ie: a list as the only child of a table cell:
<table> <tr> <td> <ul> <li>Remove me!</li> </ul> </td> </tr> </table>
If you try the document.remove trick, the entire table will be deleted because the start and end offsets for the list item is the same as for the table (they contain the same text content). Unfortunately, the new removeElement method won’t help with this because if you remove the last child element it also removes the parent element so document.removeElement(li) has the exact same effect as document.removeElement(table). The work around for that is of course to insert another element into the table cell first – most likely an empty p or p-implied element which you can do with insertBefore or insertAfter, but not if you want the table cell to be empty because you can’t insert the required p-implied and line ending with insertBefore or insertAfter. Instead, you’d have to insert an empty p tag and then use document.setParagraphAttributes to convert it to a p-implied after the fact. That or insert some text and then delete it again (but keep the trailing newline that will be inserted automatically). Both those cases will make a mess of your undo buffer because they count as two changes instead of one.