mystyleddocument.java

来自「java文件注释过滤器,将文件中的注释过滤掉.」· Java 代码 · 共 81 行

JAVA
81
字号
package homework;

import javax.swing.text.*;
import javax.swing.text.AbstractDocument.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.Color;


class MyStyledDocument extends DefaultStyledDocument {

    static SimpleAttributeSet blueAttributeSet;
    static {
        //Hard-code some attributes.
        blueAttributeSet = new SimpleAttributeSet();
        StyleConstants.setFontFamily(blueAttributeSet, "SansSerif");
        StyleConstants.setFontSize(blueAttributeSet, 13);
        StyleConstants.setForeground(blueAttributeSet, Color.blue);

    }

    public MyStyledDocument(Content c, StyleContext styles) {
        super(c, styles);
    }

    public MyStyledDocument(StyleContext styles) {
        super(styles);
    }

    public MyStyledDocument() {
        super();
    }

    public void formatDocument() {
        String str = null;
        try {
            str = getText(0, getLength());
        } catch (Exception e) {
            System.out.println(e);
            System.exit(0);
        }
        format(str, 0);
    }

    public void format(String str, int start) {
        int end;
        for (int i = start; i + 2 <= str.length(); i++) {
            if (str.substring(i, i + 2).equals("//")) {
                start = i;
                end = i + 2;
                while (end < str.length() && str.charAt(end) != '\n') {
                    end++;
                }
                if (end == str.length()) {
                    end--;
                }
                setParagraphAttributes(start, end - start + 1, blueAttributeSet, false);
                format(str, end + 1);
                return;
            }
            if (str.substring(i, i + 2).equals("/*")) {
                start = i;
                end = i + 2;
                while (end < str.length() &&
                       !str.substring(end, end + 2).equals("*/")) {
                    end++;
                }
                if (end == str.length()) {
                    end--;
                }
                setParagraphAttributes(start, end - start + 1, blueAttributeSet, true);
                format(str, end + 1);
                return;
            }
        }

    }


}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?