簡體   English   中英

如何在JTextPane中將每個字符設置為不同的顏色/背景顏色?

[英]How can I set each character to a different color/background color in a JTextPane?

我一直在尋找這個,到目前為止,我能夠想出的是如何創建一個樣式並將其應用於這樣的角色:

StyledDocument doc = (StyledDocument) new DefaultStyledDocument();
JTextPane textpane = new JTextPane(doc);
textpane.setText("Test");
javax.swing.text.Style style = textpane.addStyle("Red", null);
StyleConstants.setForeground(style, Color.RED);
doc.setCharacterAttributes(0, 1, textpane.getStyle("Red"), true); 

如果您的文檔中只有少量樣式並希望按名稱存儲它們,以便以后可以輕松應用它們,這將非常有用。 在我的應用程序中,我希望能夠為文本中的每個字符獨立設置前景色(僅少數值之一)和背景色(灰度,許多不同的值)。 為此創建潛在的數百/數千種不同風格似乎是一種巨大的浪費。 有沒有辦法設置這些屬性,而不必每次都創建一個新的樣式? 如果我只需渲染文本會更容易,但我也需要使其可編輯。 有沒有辦法用JTextPane做到這一點,還是有另一個提供此功能的swing類?

如果要更改文本窗格中每個字符的樣式,這里有一個完全隨機的方法。 您為每個字符創建不同的屬性集。 由你來找到合適的組合(前景/背景對比,字符大小差別不大等等)。 您還可以存儲已應用的不同樣式,這樣就不會使用相同的樣式兩次。

在此輸入圖像描述

import java.awt.Color;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class TestDifferentStyles {
    private void initUI() {
        JFrame frame = new JFrame(TestDifferentStyles.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        StyledDocument doc = new DefaultStyledDocument();
        JTextPane textPane = new JTextPane(doc);
        textPane.setText("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has "
                + "been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of "
                + "type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the "
                + "leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the"
                + " release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing "
                + "software like Aldus PageMaker including versions of Lorem Ipsum.");

        Random random = new Random();
        for (int i = 0; i < textPane.getDocument().getLength(); i++) {
            SimpleAttributeSet set = new SimpleAttributeSet();
            // StyleConstants.setBackground(set, new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            StyleConstants.setForeground(set, new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            StyleConstants.setFontSize(set, random.nextInt(12) + 12);
            StyleConstants.setBold(set, random.nextBoolean());
            StyleConstants.setItalic(set, random.nextBoolean());
            StyleConstants.setUnderline(set, random.nextBoolean());

            doc.setCharacterAttributes(i, 1, set, true);
        }

        frame.add(new JScrollPane(textPane));
        frame.setSize(500, 400);
        frame.setVisible(true);
    }

    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestDifferentStyles().initUI();
            }
        });
    }

}

我不確定你的意思,但是你不能循環遍歷JtextPane每個字符,並且在該循環中迭代你想要突出顯示的所有字母/字符等。有一個if語句檢查字符然后相應地設置Style

這是我做的一個例子我只為字符hw實現它以用於演示目的:

在此輸入圖像描述

//necessary imports
import java.awt.Color;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class Test {

    /**
     * Default constructor for Test.class
     */
    public Test() {
        initComponents();
    }

    public static void main(String[] args) {

        /**
         * Create GUI and components on Event-Dispatch-Thread
         */
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Test test = new Test();
            }
        });
    }

    /**
     * Initialize GUI and components (including ActionListeners etc)
     */
    private void initComponents() {
        JFrame jFrame = new JFrame();
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        StyledDocument doc = (StyledDocument) new DefaultStyledDocument();
        JTextPane textPane = new JTextPane(doc);
        textPane.setText("Hello, world! :)");

        //create necessary styles for various characters
        javax.swing.text.Style style = textPane.addStyle("Red", null);
        StyleConstants.setForeground(style, Color.RED);
        javax.swing.text.Style style2 = textPane.addStyle("Blue", null);
        StyleConstants.setForeground(style2, Color.BLUE);

        //create array of characters to check for and style
        String[] lettersToEdit = new String[]{"h", "w"};

        //create arraylist to hold each character in textPane
        ArrayList<String> strings = new ArrayList<>();

        //get all text
        String text = textPane.getText();

        //populate arraylist
        for (int i = 0; i < text.length(); i++) {
            strings.add(text.charAt(i) + "");
        }

        //declare variabe to hold position
        int position = 0;

        for (String s1 : strings) {//for each character in the textpane text
            for (String s2 : lettersToEdit) {//for each character in array to check (lettersToEdit)
                if (s2.toLowerCase().equalsIgnoreCase(s1)) {//if there was a match

                    System.out.println("found a match: " + s1);
                    System.out.println("counter: " + position + "/" + (position + 1));

                    //check which chacacter we matched
                    if (s1.equalsIgnoreCase(lettersToEdit[0])) {
                        //set appropriate style
                        doc.setCharacterAttributes(position, 1, textPane.getStyle("Red"), true);
                    }
                    if (s1.equalsIgnoreCase(lettersToEdit[1])) {
                        doc.setCharacterAttributes(position, 1, textPane.getStyle("Blue"), true);
                    }
                }
            }
            //increase position after each character on textPane is parsed
            position++;
        }

        jFrame.add(textPane);
        //pack frame (size JFrame to match preferred sizes of added components and set visible
        jFrame.pack();
        jFrame.setVisible(true);
    }
}

我認為你必須做到這一點的最好方法就像我們在編輯器中有突出顯示,不是追逐角色,而是有一個模式,例如:

private static HashMap<Pattern, Color> patternColors;
private static String GENERIC_XML_NAME = "[A-Za-z]+[A-Za-z0-9\\-_]*(:[A-Za-z]+[A-Za-z0-9\\-_]+)?";
private static String TAG_PATTERN = "(</?" + GENERIC_XML_NAME + ")";
private static String TAG_END_PATTERN = "(>|/>)";
private static String TAG_ATTRIBUTE_PATTERN = "(" + GENERIC_XML_NAME + ")\\w*\\=";
private static String TAG_ATTRIBUTE_VALUE = "\\w*\\=\\w*(\"[^\"]*\")";
private static String TAG_COMMENT = "(<\\!--[\\w ]*-->)";
private static String TAG_CDATA = "(<\\!\\[CDATA\\[.*\\]\\]>)";

private static final Color COLOR_OCEAN_GREEN = new Color(63, 127, 127);
private static final Color COLOR_WEB_BLUE = new Color(0, 166, 255);
private static final Color COLOR_PINK = new Color(127, 0, 127);

static {
    // NOTE: the order is important!
    patternColors = new LinkedHashMap<Pattern, Color>();
    patternColors.put(Pattern.compile(TAG_PATTERN), Color.BLUE); // COLOR_OCEAN_GREEN | Color.BLUE
    patternColors.put(Pattern.compile(TAG_CDATA), COLOR_WEB_BLUE);
    patternColors.put(Pattern.compile(TAG_ATTRIBUTE_PATTERN), COLOR_PINK);
    patternColors.put(Pattern.compile(TAG_END_PATTERN), COLOR_OCEAN_GREEN);
    patternColors.put(Pattern.compile(TAG_COMMENT), Color.GRAY);
    patternColors.put(Pattern.compile(TAG_ATTRIBUTE_VALUE), COLOR_OCEAN_GREEN); //Color.BLUE | COLOR_OCEAN_GREEN
}




public XmlView(Element element) {

    super(element);

    // Set tabsize to 4 (instead of the default 8).
    getDocument().putProperty(PlainDocument.tabSizeAttribute, 4);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM