2011-12-14 59 views
1

我試圖在JTextPane中替換文本顏色而不更改整個JTextPane的顏色。 我在網上發現了一個允許你這樣做的類,但是當我試圖創建一個「ColorPane」對象來運行他提供的方法時,編譯的代碼卻無法正常工作。我的筆記本電腦剛剛播放了典型的「Windows no-no sound」。 所以我現在只是想添加我需要的方法,但我得到了一些類型不匹配錯誤。JTextPane中的替代文本顏色

這裏是ColorPane類:(我只是拿出創建該表的方法) http://www.java2s.com/Code/Java/Swing-JFC/ExtensionofJTextPanethatallowstheusertoeasilyappendcoloredtexttothedocument.htm

這裏是與類型不匹配錯誤的方法: http://pastebin.com/jWtQK0Va

謝謝!

回答

1

看着你的問題,好像你想在你的JTextPane中使用多種顏色。 您只需將此方法放入您的代碼中並根據需要提供參數。

public void appendToPane(String yourText, Color colour) 
    { 
     StyleContext sc = StyleContext.getDefaultStyleContext(); 
     AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, colour); 
     aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console"); 

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

上述方法使用以下進口:

  • 進口javax.swing.text.AttributeSet;
  • import javax.swing.text.SimpleAttributeSet;
  • import javax.swing.text.StyleConstants;
  • import javax.swing.text.StyleContext;
  • import javax.swing.JTextPane;

而tPane是JTextPane的對象。就像如果你想讓你的名字顯示爲藍色一樣,請將方法稱爲appendToPane(「Your Name」,Color.BLUE);現在如果你想讓其他文本顯示爲紅色,再次調用方法appendToPane(「New Text」,Color.RED);希望這可以解決你所要求的查詢。

Regards

+0

Thanks!小錯字:STyleConstants應該是StyleConstants – adhg 2013-05-28 16:25:43