Igor
Igor

Reputation: 1602

How to implement DocumentFilter that inserts URLs as hyperlinks in JTextPane?

I have a JTable which uses JTextPane as editor and renderer. I added a keyListener to the editor, that listens for "space" character and checks if the last word is URL and if it is, adds it to the editor as a hyperlink using this attribute: attrs.addAttribute(HTML.Attribute.HREF, url);. I soon figured that this won't convert URLs to hyperlinks when I paste text so I decided I need to do this using DocumentFilter.

How can I create a DocumentFilter that checks if the text about to be inserted/replaced contains URLs and if it does inserts/replaces thoose URLs with the HTML.Attribute.HREF attribute and the rest of the text as it is?

Upvotes: 1

Views: 234

Answers (2)

StanislavL
StanislavL

Reputation: 57421

See the example http://java-sl.com/tip_autocreate_links.html It's not necessary to use a DocumentFilter. LIstener is enough.

Just mark inserted content with a dummy attribute and then replace it with hyperlink html.

Upvotes: 1

s.s.o
s.s.o

Reputation: 185

// somewhere add text reformated as html link
setText("<HTML>Click the <FONT color=\"#000099\"><U>link</U></FONT>"
        + " to go to the Java website.</HTML>");

// somewhere add a listener for clicks
addActionListener(new OpenUrlAction());

// Define uri and open action
 final URI uri = new URI("http://java.sun.com");
    class OpenUrlAction implements ActionListener {
      @Override public void actionPerformed(ActionEvent e) {
        open(uri);
      }
    }

// Define open uri method
private static void open(URI uri) {
    if (Desktop.isDesktopSupported()) {
      try {
        Desktop.getDesktop().browse(uri);
      } catch (IOException e) { /* TODO: error handling */ }
    } else { /* TODO: error handling */ }

Upvotes: -1

Related Questions