I need a JTable that has multilined cells, and converts multiple (in one cell) URLs into clickable hyperlinks and supports basic style manipulation (bold, italic, underline), which means I can edit the style during or after entering the text. I also need it to be able to save the styled cell content into database.
What is the easiest way to achieve this?
I already tried creating a custom cell editor (and sorted out the multiline issue), which uses JTextPane and added key listener to it that listens when “space” character is released and if the last word starts with “http://”, removes it from it’s document and adds it again as styled text with href attribute and blue color. I also added listeners which listen for mouse clicks on hyperlinks. It all works during edit, but when the cell loses focus all text becomes unstyled and black. Maybe because I’m using different renderer and editor, but I add the key listeners to the renderer also.
I’m also having huge problems saving and especially setting table cell values when closing and starting the app. Should I go on and try to get it to work this way, or should I go back and take a different approach, like maybe setting JTextPane’s content type to “text/html”. If I did this I don’t really know how I’ll convert URLs into hyperlinks as you type.
BTW, the editor extends AbstractCellEdit, while the renderer extends JTextPane.
Any help will be appreciated.
Robin answered you on the
JTablepart, and I will add about text.If you don’t need real HTML, i.e. with links like
<a href="http://example.com">link text</a>, then you can useDefaultStyledDocumentas the model for your cell. To make http-prefixed text appear as a link, set the color to blue and add underline attribute. (DefaultStyledDocumentmodel is simpler thanHTMLDocument.)To preserve formatting, you should store
Document, the text model in Swing, for each cell.There’s no need to remove and re-insert the text to add styling. You can apply styling to the text already in the Document, use
setCharacterAttributesmethod.And you can actually re-use the rendering engine of Swing text components to render your cells. You can fetch the root view for presentation using
TextUI.getRootView(). The view hierarchy can render your text and help you translate mouse clicks into textElements, which you can use to launch hyperlink.