Search code examples
javaswingjeditorpane

Custom JEditorPane behaviour


Hi fellow programmers!

I have a JEditorPane, where user is supposed to input series of numbers (quantities with optional uncertainities) separated by semicolons, for example:

3.0; 5.8; 70+-5; ...

The list is then mapped to ArrayList wrapper containing parsed quantities.

I'd like to implement a specific behaviour for input pane. For example pressing ';' or ' ' should insert '; ', pressing backspace/delete between ';' and ' ' should erase both of them and combine separated numbers. Cuts and pastes also have specific behaviour, and so on. I want it to be user-friendly and intuitive.

I tried DocumentFilter, but it seems to be too simple and it can mess up caret/selection. So I thought about writing my very own StyledEditorKit subclass, but there's a load of Actions to implement and a lot of technical details, which I am not certaing about.

How can I deal with it? Is there any way of doing it without writing EditorKit from scratch?


Solution

  • First of all I wouldn't use a JEditorPane for this. A JEditorPane is for displaying HTML. It will be much easier using a JTextArea or JTextPane since this only contains text and no tags to worry about.

    I tried DocumentFilter, but it seems to be too simple and it can mess up caret/selection.

    A DocumentFilter is designed to used by multiple Documents and therefore knows nothing about the actual text component you are using. If you want to control caret location then you would need to pass the text component as a parameter to your DocumentFilter class.

    pressing ';' or ' ' should insert '; ',

    If you don't like a DocumentFilter, then maybe you can use Key Bindings and handle the keyTyped event

    pressing backspace/delete between ';' and ' ' should erase both

    A DocumentFilter should work or again you can use Key Bindings. Note for the backspace key I believe you need to handle Ctrl+H.

    Cuts and pastes also have specific behaviour

    A DocumentFilter won't the reason for the update to the Document (ie user typing or user pasting. You could try overriding the cut/copy/paste methods of the text component.

    So I thought about writing my very own StyledEditorKit subclass, but there's a load of Actions to implement

    Agreed, I think this is overkill.