【问题标题】:JEditorPane content type "text/html" line breaks with no paragraph creationJEdi​​torPane 内容类型“text/html”换行符,不创建段落
【发布时间】:2020-09-08 00:26:03
【问题描述】:

当我用setContentType("text/html") 创建一个JEditorPane 并按Enter 编辑文本时,会创建一个新的html 段落(<p style="margin-top: 0">)。有没有办法插入换行符(<br>)而不是那个?

示例如下:

import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Test {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setTitle("Text Area");

        JEditorPane editor = new JEditorPane();
        editor.setContentType("text/html");

        Box pane = Box.createVerticalBox();

        pane.add(editor);
        frame.add(pane);

        frame.setSize(500, 500);

        frame.addWindowListener(new WindowAdapter()
        {
            @Override
            public void windowClosing(WindowEvent e)
            {
                System.out.println(editor.getText());
                e.getWindow().dispose();
            }
        });

        frame.setVisible(true);
    }
}

这是书面文本的输出:

<html>
  <head>

  </head>
  <body>
    <p style="margin-top: 0">
      First line
    </p>
    <p style="margin-top: 0">
      This is a new line
    </p>
  </body>
</html>

这就是我想要的:

<html>
  <head>

  </head>
  <body>
    <p style="margin-top: 0">
      First line<br>
      This is a new line
    </p>
  </body>
</html>

【问题讨论】:

  • 编辑者创建&lt;br&gt;的常用方法是使用[shift]+[enter]。试试吧。
  • 谢谢。默认情况下,JEditorPane 无法执行此操作。但是,我可以通过创建一个新操作来解决它。

标签: java html swing


【解决方案1】:

我可以为Shift + Enter 组合键创建一个新操作来解决它:

private static final String NEW_LINE = "new-line";

private static void initializeEditorPane(JEditorPane textArea) {
    HTMLEditorKit kit = new HTMLEditorKit();
    textArea.setEditorKit(kit);

    InputMap input = textArea.getInputMap();
    KeyStroke shiftEnter = KeyStroke.getKeyStroke("shift ENTER");
    input.put(shiftEnter, NEW_LINE);

    ActionMap actions = textArea.getActionMap();
    actions.put(NEW_LINE, new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                kit.insertHTML((HTMLDocument)textArea.getDocument(), textArea.getCaretPosition(),
                        "<br>", 0,0, HTML.Tag.BR);
                textArea.setCaretPosition(textArea.getCaretPosition()); // This moves caret to next line
            } catch (BadLocationException | IOException ex) {
                ex.printStackTrace();
            }
        }
    });
}

【讨论】:

  • 不错的一个!很高兴你把事情解决了。 :)
  • 非常感谢您的评论和帮助。我已经接受了答案。我也希望在以后的帖子中见到你。
猜你喜欢
  • 2021-10-15
  • 1970-01-01
  • 2011-06-06
  • 2013-04-02
  • 2012-07-29
  • 1970-01-01
  • 2011-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多