简体   繁体   English

使用JEditorPane编辑html文本

[英]Editing html text with JEditorPane

I wrote a text editor that saves the text as html. 我写了一个文本编辑器,将文本另存为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. 我在使用粗体,斜体等样式时没有问题,唯一的问题是按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: 我认为这与<p>标记有关,但是我不确定...无论如何,这是我的问题的一个示例:

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. 我认为您正在尝试在呈现HTML之后直接在JEditorPane上进行编辑。 JEditorPane reads in the text you provide it and renders it in accordance with the HTML markup that accompanies the text. JEdi​​torPane读取您提供的文本,并根据文本随附的HTML标记进行呈现。 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: 因此,如果要在文本的某个位置使其具有换行符,则需要输入一个break标记,如下所示:

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. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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