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

ぬりえタグをJTextPane付けて使います。HTMLEditorKit

または、 with を使用JEditorPane/JTextPaneStyledEditorKitてテキストの色を指定することもできますStyleConstants.setForeground()

于 2012-03-05T13:00:31.973 に答える