javaswingnewlineparagraphhtmleditorkit

Behavior of <enter> key in JEditorPane (with HtmlEditorKit)


If I put the cursor in the middle of <p>A line of text</p> and hit enter I get

<p>A line</p>
<p>of text</p>

This is on my Linux dev machine.

When I run the same application on a Windows machine, I get

<p>A line
of text</p>

i.e. a \n inserted instead of creating an extra <p> element. Since \n is just rendered as a space in HTML, enter basically doesn't work when I'm on Windows.

Question: How do I force the insert <p> behavior upon enter on Windows?


Solution

  • According to Key Bindings the Enter key is mapped to the "insert-break" Acton.

    In Windows this Action is defined in the DefaultEditorKit:

    public static class InsertBreakAction extends TextAction {
    
        /**
         * Creates this object with the appropriate identifier.
         */
        public InsertBreakAction() {
            super(insertBreakAction);
        }
    
        /**
         * The operation to perform when this action is triggered.
         *
         * @param e the action event
         */
        public void actionPerformed(ActionEvent e) {
            JTextComponent target = getTextComponent(e);
            if (target != null) {
                if ((! target.isEditable()) || (! target.isEnabled())) {
                    UIManager.getLookAndFeel().provideErrorFeedback(target);
                    return;
                }
                target.replaceSelection("\n");
            }
        }
    }
    

    and simply adds "\n" as you suggest.

    If you have different behaviour on Linux then I would guess a custom Action is added to the HTMLEditorKit to insert the paragraph tag.

    So I would suggest you need to find that Action and then add it to the HTMLEditorKit in the Windows platform.