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

时间:2015-09-07 07:44:48

标签: java html jtextarea

我在为来自

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

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

<p>something like this</p><br>等。 这也不是一个Web应用程序。如果您有任何想法如何做到这一点。建议我。谢谢。

更新

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

标签。

我将在输入此文本后直接向用户发送电子邮件,因此格式化非常重要。

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

2 个答案:

答案 0 :(得分:2)

  

例如,如果我输入包含换行符的文字,则会自动插入<br><p>

基本要求是在键入enter时使用DocumentFilter注入标记

Markup

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>“可能会”更难,但是,如果您认为第一行以<p>开头,则只需注入</p>在换行符之前和<p>之后,然后附加剩余的文本......

更新了段落支持和粘贴

显然我不能走开......

Markup

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);
                        }
                    }
                }

            });
        }
    }
}

答案 1 :(得分:0)

也许你需要这样的东西:

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