2012-03-05 66 views
2

我有一個文件,我將逐行讀取它。通過使用拆分方法將每行分割成單詞,並根據單詞的位置(每行的前4個字符等)以及基於單詞對單詞着色。不同的顏色應該適用於下面的不同的單詞。我想知道哪一類是有用的,我看着熒光筆。任何建議,與例如將是非常有益在java中着色文本

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 
} 

回答

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

+0

謝謝,這就是我正在尋找。我會盡力回覆。 – FirmView 2012-03-05 13:16:37

+1

@FirmView:你的歡迎,併成爲我的客人,我可以幫助你,我會:-) – 2012-03-05 13:31:32

+2

*「一個示例程序片段:」*很奇怪,你應該給這些單詞添加'片段'。我的意思是 - '片段'通常表達'短',但在編程環境中,它也意味着(至少對我而言)「缺少更多代碼就無法工作」。示例程序已準備就緒。 (代碼和屏幕截圖爲+1) – 2012-03-05 13:54:25

5

使用JTextPaneHTMLEditorKit添加着色標記。

或者你可以使用JEditorPane/JTextPaneStyledEditorKit和使用StyleConstants.setForeground()