在JTextPane中呈现降价格式的问题

时间:2013-01-12 13:42:46

标签: java swing render markdown jtextpane

我正在使用Swing创建一个简单的降价文本编辑器,它可以在其主JTextPane中实现markdown格式。也就是说,像*hello*这样的降价格式文本一旦检测到就会以斜体显示,但会以纯文本格式保存。

为此,我提出了一个正则表达式来获取markdown标记(现在让我们只使用*italics*作为示例),每隔几秒我的代码就会搜索JTextPane的文本并使用JTextPane #setCharacterAttributes更改相关区域的格式。

// init
PLAIN = Document.addStyle("plain", null);
StyleConstants.setFontSize(PLAIN, 12);

ITALIC = Document.addStyle("italic", null);
StyleConstants.setItalic(ITALIC, true);
...
// every few seconds
// remove all formatting
Document.setCharacterAttributes(0, Document.getLength(), PLAIN, true);

// italicize parts that the regex matches
m = Pattern.compile("\\*([^\\n*]+)\\*").matcher(temp);
while (m.find()) {
    Document.setCharacterAttributes(m.start(), m.group().length(), ITALIC, false);
}

问题在于“活跃” - 经过一段时间后,JTextPane开始按characters instead of words换行,有时会完全丢失自动换行,只显示未打包的行。

有什么办法可以解决这个问题/扩展JTextPane来修复它,还是JTextPane根本不适合这样的实时更新?我用谷歌搜索了很长时间但找不到任何东西;我只是不确定要搜索什么。

package test;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.lang.reflect.Field;
import java.util.logging.*;
import java.util.regex.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;

public class Test {

    private JFrame frame = new JFrame();
    private JTextPane jtp;
    private StyledDocument doc;

    // NEW LINES
    private Timer T;
    private boolean update = true;
    MarkdownRenderer m;
    // END OF NEW LINES

    public Test() {
        jtp = new JTextPane();
        jtp.setEditorKit(new MyStyledEditorKit());
        jtp.setText("\ntype some text in the above empty line and check the wrapping behavior");
        doc = jtp.getStyledDocument();
        // NEW LINES
        m = new MarkdownRenderer(jtp);
        Timer T = new Timer(2000, new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (update) {
                    update = false;
                    m.render();
                }
            }
        });
        T.start();
        // END OF NEW LINES
        doc.addDocumentListener(new DocumentListener() {

            private boolean doUpdate = true;
            public void insertUpdate(DocumentEvent e) {
                insert();
            }

            public void removeUpdate(DocumentEvent e) {
                insert();
            }

            public void changedUpdate(DocumentEvent e) {
//                triggers every time formatting is changed
//                 insert();
            }

            public void insert() {
                SwingUtilities.invokeLater(new Runnable() {

                    public void run() {
                        Style defaultStyle = jtp.getStyle(StyleContext.DEFAULT_STYLE);
                        doc.setCharacterAttributes(0, doc.getLength(), defaultStyle, false);
                        update = true;
                    }
                });
            }
        });
        JScrollPane scroll = new JScrollPane(jtp);
        scroll.setPreferredSize(new Dimension(200, 200));
        frame.add(scroll);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                Test bugWrapJava7 = new Test();
            }
        });
    }
}

class MyStyledEditorKit extends StyledEditorKit {
    private MyFactory factory;

    public ViewFactory getViewFactory() {
        if (factory == null) {
            factory = new MyFactory();
        }
        return factory;
    }
}

class MyFactory implements ViewFactory {
    public View create(Element elem) {
        String kind = elem.getName();
        if (kind != null) {
            if (kind.equals(AbstractDocument.ContentElementName)) {
                return new MyLabelView(elem);
            } else if (kind.equals(AbstractDocument.ParagraphElementName)) {
                return new ParagraphView(elem);
            } else if (kind.equals(AbstractDocument.SectionElementName)) {
                return new BoxView(elem, View.Y_AXIS);
            } else if (kind.equals(StyleConstants.ComponentElementName)) {
                return new ComponentView(elem);
            } else if (kind.equals(StyleConstants.IconElementName)) {
                return new IconView(elem);
            }
        }

        // default to text display
        return new LabelView(elem);
    }
}

class MyLabelView extends LabelView {
    public MyLabelView(Element elem) {
        super(elem);
    }
    public View breakView(int axis, int p0, float pos, float len) {
        if (axis == View.X_AXIS) {
            resetBreakSpots();
        }
        return super.breakView(axis, p0, pos, len);
    }

    private void resetBreakSpots() {
        try {
            // HACK the breakSpots private fields
            Field f=GlyphView.class.getDeclaredField("breakSpots");
            f.setAccessible(true);
            f.set(this, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


class MarkdownRenderer {    
    private static final MutableAttributeSet PLAIN = new SimpleAttributeSet();
    private static final MutableAttributeSet BOLD = new SimpleAttributeSet();
    private static final MutableAttributeSet ITALIC = new SimpleAttributeSet();
    private static final MutableAttributeSet UNDERLINE = new SimpleAttributeSet();

    private StyledDocument Document = null;

    public MarkdownRenderer(JTextPane editor) {
        Document = (StyledDocument) editor.getDocument();

        StyleConstants.setBold(BOLD, true);
        StyleConstants.setItalic(ITALIC, true);
        StyleConstants.setUnderline(UNDERLINE, true);
    }

    void render() {
        String s = "";
        try {
            s = Document.getText(0, Document.getLength());
        } catch (BadLocationException ex) {
            Logger.getLogger(MarkdownRenderer.class.getName()).log(Level.SEVERE, null, ex);
        }
//        Document.setCharacterAttributes(0, Document.getLength(), PLAIN, true);

        String temp = s.replaceAll("\\*\\*([^\\n*]+)\\*\\*", "|`$1`|"); // can also use lazy quantifier: (.+?)

        Matcher m = Pattern.compile("\\|`.+?`\\|").matcher(temp);
        while (m.find()) {
            Document.setCharacterAttributes(m.start(), m.group().length(), BOLD, false);
        }
        m = Pattern.compile("\\*([^\\n*]+)\\*").matcher(temp);
        while (m.find()) {
            Document.setCharacterAttributes(m.start(), m.group().length(), ITALIC, false);
        }
        m = Pattern.compile("_+([^\\n*]+)_+").matcher(temp);
        while (m.find()) {
            Document.setCharacterAttributes(m.start(), m.group().length(), UNDERLINE, false);
        }
    }
}

0 个答案:

没有答案
相关问题