如何为 JTextArea 中的文本生成 html?

How to generate html for text in JTextArea?

我在为来自

的给定字符串生成 html 代码时遇到问题
JTextArea textArea=new JTextArea(10,10);
String textToHtml=textArea.getText();

在此生成的 html 代码中,它应包含与给定字符串相关的所有 html 标签。

喜欢<p>something like this</p><br>等。 这也不是网络应用程序。如果你知道怎么做。建议我。谢谢。

更新

例如,如果我键入带有换行符的文本,它应该会自动插入 <br><p>。 Dreamweaver 中就有这种功能。当您开始在网页中填充内容时,它会自动插入代码。问题是我不希望非技术用户在编写段落时键入 HTML 代码,因为默认情况下会插入

标记和所有标记。键入此文本后,我将直接通过电子邮件将其发送给用户,因此此格式很重要。

需要注意的是,我不知道用户会输入什么,这完全取决于他。所以无论我使用什么方法都应该能够识别它可以放置标签的地方(比如段落标签)并继续

也许你需要这样的东西:

String textToHtml="something like this";
textToHtml = "<p>".concat(textToHtml).concat("</p>").concat("<br>");

For an example, if I type a text with line breaks, it should automatically insert <br> or <p>

基本要求是使用 DocumentFilter 在他们键入 enter

时注入您的标记

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class TestMarkup {

    public static void main(String[] args) {
        new TestMarkup();
    }

    public TestMarkup() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static class TestPane extends JPanel {

        public TestPane() {
            setLayout(new BorderLayout());
            JTextArea ta = new JTextArea(10, 20);
            add(new JScrollPane(ta));

            ((AbstractDocument) ta.getDocument()).setDocumentFilter(new DocumentFilter() {

                @Override
                public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
                    if (text.endsWith("\n")) {
                        super.replace(fb, offset, 0, "<br>", attrs);
                        offset += 4;
                    }
                    super.replace(fb, offset, length, text, attrs);
                }

            });
        }
    }
}

插入 <p>/</p> "might" 会更困难,但是,如果您假设您的第一行以 <p> 开头,则只需注入 </p> 在换行符之前和 <p> 在它之后,然后附加剩余的文本...

更新了段落支持和粘贴

看来我就是走不开...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.StringJoiner;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.Element;

public class TestMarkup {

    public static void main(String[] args) {
        new TestMarkup();
    }

    public TestMarkup() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static class TestPane extends JPanel {

        public TestPane() {
            setLayout(new BorderLayout());
            JTextArea ta = new JTextArea(10, 20);
            add(new JScrollPane(ta));

            ((AbstractDocument) ta.getDocument()).setDocumentFilter(new DocumentFilter() {

                protected String getLastLineOfText(Document document) throws BadLocationException {
                    // Find the last line of text...
                    Element rootElem = document.getDefaultRootElement();
                    int numLines = rootElem.getElementCount();
                    Element lineElem = rootElem.getElement(numLines - 1);
                    int lineStart = lineElem.getStartOffset();
                    int lineEnd = lineElem.getEndOffset();
                    String lineText = document.getText(lineStart, lineEnd - lineStart);
                    return lineText;
                }

                @Override
                public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
                    if (text.length() > 1) {

                        String lastLineOfText = getLastLineOfText(fb.getDocument());
                        if (!lastLineOfText.startsWith("<p>")) {
                            if (!text.startsWith("<p>")) {
                                text = "<p>" + text;
                            }
                        }

                        // Replace any line breaks with a new line
                        String[] lines = text.split("\n");
                        if (lines.length > 0) {

                            StringJoiner sj = new StringJoiner("<br>\n");
                            for (String line : lines) {
                                sj.add(line);
                            }
                            text = sj.toString();

                        }

                        if (!text.endsWith("</p>")) {
                            text += "</p>";
                        }

                        super.replace(fb, offset, length, text, attrs);

                    } else {

                        String postInsert = null;
                        if (text.endsWith("\n")) {

                            // Find the last line of text...
                            String lastLineOfText = getLastLineOfText(fb.getDocument());
                            lastLineOfText = lastLineOfText.substring(0, lastLineOfText.length() - 1);
                            postInsert = "<p>";
                            if (!lastLineOfText.endsWith("</p>")) {

                                super.replace(fb, offset, 0, "</p>", attrs);
                                offset += 4;
                            }
                        }
                        super.replace(fb, offset, length, text, attrs);
                        if (postInsert != null) {
                            offset += text.length();
                            super.replace(fb, offset, 0, "<p>", attrs);
                        }
                    }
                }

            });
        }
    }
}