【问题标题】:Alternate Text Color in JTextPaneJTextPane 中的替代文本颜色
【发布时间】:2012-01-20 08:54:19
【问题描述】:

我正在尝试在 JTextPane 中替换文本颜色而不更改整个 JTextPane 的颜色。 我在网上找到了一个允许您执行此操作的课程,但是当我尝试创建一个“ColorPane”对象以运行他提供的方法时,代码已编译但根本不起作用。我的笔记本电脑只是播放典型的“Windows no-no sound”。 所以我现在尝试添加我需要的方法,但我遇到了一些类型不匹配的错误。

这里是 ColorPane 类:(我刚刚取出了创建表的方法) http://www.java2s.com/Code/Java/Swing-JFC/ExtensionofJTextPanethatallowstheusertoeasilyappendcoloredtexttothedocument.htm

这是类型不匹配错误的方法: http://pastebin.com/jWtQK0Va

谢谢!

【问题讨论】:

    标签: swing types colors jtextpane mismatch


    【解决方案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;
    • 导入 javax.swing.text.SimpleAttributeSet;
    • 导入 javax.swing.text.StyleConstants;
    • 导入 javax.swing.text.StyleContext;
    • 导入 javax.swing.JTextPane;

    而tPane 是JTextPane 的对象。就像您希望您的姓名以蓝色显示一样,将方法调用为 appendToPane("Your Name", Color.BLUE);现在,如果您希望其他文本显示为红色,则再次调用该方法 appendToPane("New Text", Color.RED);。希望这将解决您要求的查询。

    问候

    【讨论】:

    • 谢谢!小错误:STyleConstants 应该是 StyleConstants
    猜你喜欢
    • 1970-01-01
    • 2013-10-06
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 2011-01-27
    • 2011-08-29
    • 2016-02-05
    • 1970-01-01
    相关资源
    最近更新 更多