2013-04-10 12 views
0

我目前正在處理一個給我的舊項目,它目前使用java swing並且有一個基本的gui。它有一個ColorPane,它擴展了Jtextpane以更改所選文本的顏色。ColorPane - 可以抓住不同角色的字符串嗎?

它採用本法干擾

public void changeSelectedColor(Color c) { 
     changeTextAtPosition(c, this.getSelectionStart(), this.getSelectionEnd()); 
    } 

都說字符串=的 「Hello World!」你好顏色是綠色的世界是黑色的。我如何根據Jtextpane的顏色來抓取Hello。我已經嘗試過這種笨重的方式,只是在我改變顏色的同時存儲選定的單詞,但是有沒有辦法可以一次抓住所有綠色文本?我嘗試了谷歌搜索,但...它並沒有真正想出任何好的方法。 任何人都可以指向正確的方向嗎?

回答

2

很可能有許多方法可以做到這一點,但...

你需要去的StyleDocument參考正在備份的JTextPane,在給定的字符位置開始,你需要檢查字符給定顏色的屬性,如果true繼續到文本字符,否則你完成。

import java.awt.Color; 
import javax.swing.JTextPane; 
import javax.swing.text.BadLocationException; 
import javax.swing.text.Element; 
import javax.swing.text.Style; 
import javax.swing.text.StyleConstants; 
import javax.swing.text.StyledDocument; 

public class Srap { 

    public static void main(String[] args) { 
     JTextPane textPane = new JTextPane(); 
     StyledDocument doc = textPane.getStyledDocument(); 

     Style style = textPane.addStyle("I'm a Style", null); 
     StyleConstants.setForeground(style, Color.red); 

     try { 
      doc.insertString(doc.getLength(), "BLAH ", style); 
     } catch (BadLocationException ex) { 
     } 

     StyleConstants.setForeground(style, Color.blue); 

     try { 
      doc.insertString(doc.getLength(), "BLEH", style); 
     } catch (BadLocationException e) { 
     } 

     Color color = null; 
     int startIndex = 0; 
     do { 
      Element element = doc.getCharacterElement(startIndex); 
      color = doc.getForeground(element.getAttributes()); 
      startIndex++; 
     } while (!color.equals(Color.RED)); 
     startIndex--; 

     if (startIndex >= 0) { 

      int endIndex = startIndex; 
      do { 
       Element element = doc.getCharacterElement(endIndex); 
       color = doc.getForeground(element.getAttributes()); 
       endIndex++; 
      } while (color.equals(Color.RED)); 
      endIndex--; 
      if (endIndex > startIndex) { 
       try { 
        String text = doc.getText(startIndex, endIndex); 
        System.out.println("Red text = " + text); 
       } catch (BadLocationException ex) { 
        ex.printStackTrace(); 
       } 
      } else { 
       System.out.println("Not Found"); 
      } 
     } else { 
      System.out.println("Not Found"); 
     } 
    } 
} 

這個例子簡單認定爲紅色的第一部作品,但是你可以很容易地遍歷整個文檔,並找到所有你想要的話......

+0

嗯,我知道我可以沒有知道我是否可以對待這種類似html,但我想它遵循一般模式 – 2013-04-10 04:30:55

+0

它不是HTML。這是屬性信息如何存儲在JTextPane的'StyledDocument'中。這就是它適用於所有StyledDocuments的原因,包括HTML文檔 – MadProgrammer 2013-04-10 04:31:46

相關問題