Articles Projects Tips Downloads Contacts About
 

Autocreation links from user typed text in JEditorPane with HTMLEditorKit.

A good practice in editors is to create links automatically as soon as user typed it (e.g. some text started from "www" or "http"). Something similar is possible in JEditorPane with HTMLEditorKit. The feature implementation is described below.

We just add a DocumentListener to HTMLDocument in the JEditorPane to listen break chars typing The example listens 3 chars - space, return, and tab (' ', '\n', '\t') chars. When the char is typed we checks whether the text before the typed chars starts with "www". If such a case found we at first turn it into a separate text Element by applying dummy attribute and then replace the element by link via outer HTML change method of HTMLDocument.

The screenshot shows how it looks like:

The example code is below:

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.SimpleAttributeSet;

import javax.swing.text.Utilities;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import java.io.IOException;
 
public class AutocreateLinks extends JTextPane {

    boolean isInProgress=false;
 
    public static void main(String[] args) {
        JFrame frame = new JFrame("Autocreate links during user typing example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final AutocreateLinks app = new AutocreateLinks();
        app.setEditorKit(new HTMLEditorKit());
        app.setContentType("text/html");
        app.initListener();
        JScrollPane scroll = new JScrollPane(app);
        frame.getContentPane().add(scroll);
 
        frame.setSize(400, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
 
    public AutocreateLinks() {
        super();
    }
 
    private void initListener() {
        getDocument().addDocumentListener(new DocumentListener(){
            public void insertUpdate(DocumentEvent event) {
                final DocumentEvent e=event;
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        if (e.getDocument() instanceof HTMLDocument
                                && e.getOffset()>0
                                && e.getLength()==1
                                && !isInProgress) {
                            try {

                                HTMLDocument doc=(HTMLDocument)e.getDocument();
                                String text=doc.getText(e.getOffset(), e.getLength());
                                if (text.charAt(0)==' ' || text.charAt(0)=='\n' || text.charAt(0)=='\t') {
                                    int start=Utilities.getWordStart(AutocreateLinks.this, e.getOffset()-1);
                                    text=doc.getText(start, e.getOffset()-start);
                                    if (text.startsWith("www")) {
                                        isInProgress=true;
                                        HTMLEditorKit kit=(HTMLEditorKit)getEditorKit();
                                        //the next 3 lines are necessary to create separate text elem
                                        //to be replaced with link
                                        SimpleAttributeSet a=new SimpleAttributeSet();
                                        a.addAttribute("DUMMY_ATTRIBUTE_NAME","DUMMY_ATTRIBUTE_VALUE");
                                        doc.setCharacterAttributes(start, text.length(), a, false);
 
                                        Element elem=doc.getCharacterElement(start);
                                        String html="<a href='"+text+"'>"+text+"</a>";
                                        doc.setOuterHTML(elem, html);
                                        isInProgress=false;
                                    }
                                }
                            } catch (BadLocationException e1) {
                                e1.printStackTrace();
                            } catch (IOException e1) {
                                e1.printStackTrace();
                            }
                        }
                    }
                });
            }
            public void removeUpdate(DocumentEvent e) {
            }
            public void changedUpdate(DocumentEvent e) {
            }
        });
    }

 
}