在java中着色文本

时间:2012-03-05 12:57:19

标签: java swing fonts colors jtextcomponent

我有一个文件,我将逐行阅读。通过使用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
}

2 个答案:

答案 0 :(得分:6)

如果您希望不同的文字文字具有不同的颜色,则必须阅读How to use Editor Pane or 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 EXAMPLE

答案 1 :(得分:5)

JTextPane使用HTMLEditorKit添加着色标记。

或者您可以将JEditorPane/JTextPaneStyledEditorKit一起使用,并使用StyleConstants.setForeground()指定文字颜色