Question

I'm trying to make a custom TransferHandler that will strip some text when I paste into a JEditorPane. But when I set my JEditorPane with my TransferHandler, copying and cutting no longer function. Is there a way to get it back? All I really want to customize is the pasting function.

Here is how I set up my JEditorPane:

JEditorPane jep= new JEditorPane();

myTransferHandler th = new myTransferHandler();
jep.setTransferHandler(th);

This is my TransferHandler class:

public class myTransferHandler extends TransferHandler {
    @Override
    public boolean importData(TransferHandler.TransferSupport support) {
        JEditorPane jep = (JEditorPane) support.getComponent();
        HTMLDocument doc = (HTMLDocument) jep.getDocument();
        int offset = jep.getCaretPosition();
        try {
            Object data = support.getTransferable().getTransferData(new DataFlavor(String.class, "String"));
            if(jep.getSelectedText() != null)
                //remove any highlighted text
                jep.getDocument().remove(jep.getSelectionStart(), jep.getSelectionEnd() - jep.getSelectionStart());
            doc.insertString(offset, (String) data, null);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("Insert String failed");
            e.printStackTrace();
            return false;
        }
        return true;
    }               
}

I read in this tutorial (in the "Note" section) that if I install my own TransferHandler, it won't allow me to do other types of transfers (like cutting and copying)?? Does that mean if I use a custom TransferHandler, I'd have to implement the entire class???

Any help is appreciated! Thanks!

Was it helpful?

Solution 2

So I found a solution to my problem. I only wanted to paste plain text into my JEditorPane. When you set the Content Type of the JEditorPane to "text/html" to display html code, copying from a website and pasting to the JEditorPane will add on extra html content that I didnt want (like Rich Text formatted stuff). That is why I was searching for a way to just paste plain text.

I used this TextTransferHandler to do so.

OTHER TIPS

the JEditorPane uses a subclass from transferhandler, a so called TextTransferHandler; you should subclass that TextTransferHandler, but unfortunately it's a private class.

you can copy the source code from javax.swing.plaf.basic.BasicTextUI.TextTransferHandler and make your own (copyOf) TextTransferHandler.

That textTransferHandler should do all you want...

http://j6a.ru/_basic_text_u_i_8java_source.html

line 2175

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top