使用颜色代码以编程方式格式化字符串

时间:2015-05-31 06:41:23

标签: java swing colors formatting jtextpane

我有16个字符对(例如§c,每个代码以§开头,后跟0-9或a-f)代表java.awt.Color。这是两个例子:

  1. §a是Color.getHSBColor(0.333f,1.000f,1.000f);
  2. §6是Color.getHSBColor(0.167f,1.000f,0.502f);
  3. 我需要一种方法将String的颜色设置为这些颜色的任意组合。

    Example: §aThis text is green, but §6this text is gold.
    Formatted: <green>This text is green, but <gold>this text is gold
    

    请注意&lt;&gt;标签只是示例,我需要使用以下方法在JTextPane中实际设置颜色:

    public void append(Color c, String s)
    {
        try
        {
            SimpleAttributeSet sas = new SimpleAttributeSet();
            StyleConstants.setForeground(sas, c);
    
            this.getDocument().insertString(getDocument().getLength(), s, sas);
        }
        catch (BadLocationException ex) { ex.printStackTrace();}
    }
    

    到目前为止,我的方法还没有奏效。我已经看过几个接近的问题,但没有一个与改变文本有关,取决于'颜色代码'。

    Tl; dr - 我需要一种方法,使用颜色代码以编程方式将格式化文本插入JTextPane。

0 个答案:

没有答案
相关问题