如何在JTextArea中为文本生成html? [英] How to generate html for text in JTextArea?

查看:173
本文介绍了如何在JTextArea中为文本生成html?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在为给定字符串生成html代码时遇到问题,该字符串来自

I have a problem in generating html code for a given string which is from

JTextArea textArea=new JTextArea(10,10);
String textToHtml=textArea.getText();

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

In this generated html code, it should contain with all html tags which are related to the given string.

喜欢< p>类似这样的< / p> < br> ; 等等。
此外,这不是一个Web应用程序。如果您有任何想法如何做到这一点。建议我。谢谢。

Like <p>something like this</p>, <br> and etc. Also this is not a web application. If you have any idea how do this. Suggest me. Thanks.

更新

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

标签和所有内容。输入此文本后,我会直接向用户发送电子邮件,因此格式化非常重要。

For an example, if I type a text with line breaks, it should automatically insert <br> or <p>. This kind of function is available in Dreamweaver. It automatically inserts the code when you start filling the content in the webpage. The issue is so I don't want the non-technical usres to type the HTML code when they are writing paragraphs, because by default the

tag and all are inserted. I will be emailing this directly to the user after this text is typed, so this formatting is essential.

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

It is important to note that I don't know what the user will type, it is all upto him. so whatever the method I use should be capable of identfying the places where it could put tags (like paragraph tag) and move on

推荐答案


例如,如果我输入带换行符的文本,它应自动插入< br> < ; p>

基本要求是使用 DocumentFilter 在他们输入时输入你的标记

The basic requirement would be to use a DocumentFilter to inject your markup when ever they type 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> 可能会更难,但是,如果您认为第一行以< p> ,这只是在换行符和< / p> 的问题>< p> 之后,然后附加剩余的文字......

Inserting <p>/</p> "might" be more difficult, but, if you assume that your first line starts with <p>, it's just a matter of inject </p> before the newline and <p> after it, then append the remaining text...

更新了段落支持和粘贴

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

Apparently I just can't walk away...

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

            });
        }
    }
}

这篇关于如何在JTextArea中为文本生成html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆