2

我有一个文件,我将逐行读取它。使用 split 方法将每行拆分为单词,并根据单词的位置(每行的前 4 个字符等)以及单词为单词着色。不同的颜色应该应用于不同的单词,如下所示。我想知道哪个类有用,我研究了荧光笔。任何建议,例如,将非常有帮助

String text = textArea.getText();
String newLine = "\n";
String spaceDelim = "[ ]+";
String[] tokens;
String lines = text.split(newLine);
for(String line : lines) {
    tokens = line.split(spaceDelim);
    tokens[1] //should be in redColor
    tokens[2] //should be in greenColor
    tokens[3] tokens[4] //should in blueColor
}
4

2 回答 2

6

如果您想让不同的文本文字具有不同的颜色,您必须阅读有关如何使用编辑器窗格或 TextPane的信息。这将帮助你。

一个示例程序:

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.border.*;

import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;

public class TextPaneTest extends JFrame
{
    private JPanel topPanel;
    private JTextPane tPane;

    public TextPaneTest()
    {
        topPanel = new JPanel();        

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);            

        EmptyBorder eb = new EmptyBorder(new Insets(10, 10, 10, 10));

        tPane = new JTextPane();                
        tPane.setBorder(eb);
        //tPane.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
        tPane.setMargin(new Insets(5, 5, 5, 5));

        topPanel.add(tPane);

        appendToPane(tPane, "My Name is Too Good.\n", Color.RED);
        appendToPane(tPane, "I wish I could be ONE of THE BEST on ", Color.BLUE);
        appendToPane(tPane, "Stack", Color.DARK_GRAY);
        appendToPane(tPane, "Over", Color.MAGENTA);
        appendToPane(tPane, "flow", Color.ORANGE);

        getContentPane().add(topPanel);

        pack();
        setVisible(true);   
    }

    private void appendToPane(JTextPane tp, String msg, Color c)
    {
        StyleContext sc = StyleContext.getDefaultStyleContext();
        AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);

        aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
        aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);

        int len = tp.getDocument().getLength();
        tp.setCaretPosition(len);
        tp.setCharacterAttributes(aset, false);
        tp.replaceSelection(msg);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    new TextPaneTest();
                }
            });
    }
}

这是这段代码的输出:

JTextPANE 示例

于 2012-03-05T13:01:39.067 回答
5

JTextPaneHTMLEditorKit添加着色标签一起使用。

或者您可以使用JEditorPane/JTextPanewithStyledEditorKit并指定文本颜色StyleConstants.setForeground()

于 2012-03-05T13:00:31.973 回答