2011-12-14 58 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