简体   繁体   中英

Editing html text with JEditorPane

I wrote a text editor that saves the text as html.

I'm having no problem with the styles like bold, italic, etc etc, the only problem I'm having is the way it behaves when I press enter. Instead of creating a new normal line, it creates a extra spaced line. I think it has something to do with the <p> tag but I'm not sure... Anyway here's an example of my problem:

import java.awt.BorderLayout;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.text.html.HTMLEditorKit;

public class test extends JFrame {

    public static void main(String[] args){
        new test().open();
    }

    private void open() {
        setSize(200, 200);
        JEditorPane jp = new JEditorPane();
        setLayout(new BorderLayout());
        add(jp, BorderLayout.CENTER);

        jp.setEditorKit(new HTMLEditorKit());
        jp.setText("<html><body><p>hey</p><p>Write in here</p></body></html>");
        setVisible(true);
    }
}

Is there anyway to fix this?

I think you are trying to edit directly onto the JEditorPane after it renders the HTML. JEditorPane reads in the text you provide it and renders it in accordance with the HTML markup that accompanies the text. So, if you want to make it have a newline at some point in your text, then you need to input a break tag, like so:

public class test extends JFrame
{
  public static void main(String[] args){
    test t = new test();
    t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    t.open();
  }

  private void open()
  {
    setSize(200, 200);
    JEditorPane jp = new JEditorPane();
    jp.setEditable(false);
    setLayout(new BorderLayout());
    add(jp, BorderLayout.CENTER);

    jp.setEditorKit(new HTMLEditorKit());
    jp.setText("<html><body><p>hey</p><p>Don't write here.<br>Let JEditor rendor your HTML text. </p></body></html>");
    setVisible(true);
  }
}

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM