Java 在JTextPane中基于颜色代码对文本进行动态着色

Java 在JTextPane中基于颜色代码对文本进行动态着色,java,string,swing,jtextpane,Java,String,Swing,Jtextpane,我正在尝试使用StyledDocument创建一个textpane,其中when doc.insertString(doc.getLength(),text+“\n”,关键字);它用颜色替换“§”的所有实例,然后替换一个数字(类似“§1”),并应删除其后面的代码,并使文本保持彩色。代码可以着色和删除,但问题是,当我从实际文档(textpane)中删除文本时,我拥有的局部变量没有更新,我不确定最好的方法是什么(局部变量是“text”)。问题是它开始删除代码以外的内容,我认为这是由错误的索引引起的

我正在尝试使用StyledDocument创建一个textpane,其中when doc.insertString(doc.getLength(),text+“\n”,关键字);它用颜色替换“§”的所有实例,然后替换一个数字(类似“§1”),并应删除其后面的代码,并使文本保持彩色。代码可以着色和删除,但问题是,当我从实际文档(textpane)中删除文本时,我拥有的局部变量没有更新,我不确定最好的方法是什么(局部变量是“text”)。问题是它开始删除代码以外的内容,我认为这是由错误的索引引起的

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Label;

import javax.swing.JFrame;
import java.awt.geom.Ellipse2D;

import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JLabel;
import javax.swing.JScrollPane;

import me.woder.bot.Client;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;

public class TorchGUI extends JPanel{
  private static final long serialVersionUID = 1L;
  public JFrame frame;
  private JTextField textField;
  Client c;
  JTextPane chat;
  JTextArea status;

  final StyleContext cont = StyleContext.getDefaultStyleContext();
  final AttributeSet black = cont.addAttribute(cont.getEmptySet(),     StyleConstants.Foreground, new Color(0,0,0));
  final AttributeSet blue = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, new Color(0,0,170));
  final AttributeSet green = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, new Color(0,170,0));
  final AttributeSet dark_aqua = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, new Color(0,170,170));
  final AttributeSet dark_red = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, new Color(170,0,0));
  final AttributeSet purple = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, new Color(170,0,170));
  final AttributeSet orange = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, new Color(255,170,0));
  final AttributeSet grey = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, new Color(170,170,170));
  final AttributeSet dark_grey = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, new Color(85,85,85));
  final AttributeSet indigo = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, new Color(85,85,255));
  final AttributeSet bright_green = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, new Color(85,255,85));
  final AttributeSet aqua = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, new Color(85,255,255));
  final AttributeSet red = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, new Color(255,85,85));
  final AttributeSet pink = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, new Color(255,85,255));
  final AttributeSet yellow = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, new Color(255,255,85));
  final AttributeSet white = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, new Color(255,255,255));
  final AttributeSet reset = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, Color.black);
  final AttributeSet attrBlack = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, Color.BLACK);
  DefaultStyledDocument doc = new DefaultStyledDocument() {
    private static final long serialVersionUID = 1L;

  };

/** launch it up
 * 
 */public static void main(String[] args){
     TorchGUI window;
     window = new TorchGUI();
     window.frame.setVisible(true);
     window.addText("§0this should be black §1this should be blue");
  }


/**
 * Create the application.
 */
public TorchGUI(/*Client c*/) {
    //this.c = c;
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame("TorchBot 2.1");
    frame.setBounds(100, 100, 944, 555);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(10, 11, 520, 454);
    frame.getContentPane().add(scrollPane);

    chat = new JTextPane(doc);
    scrollPane.setViewportView(chat);
    chat.setEditable(false);


    textField = new JTextField();
    textField.setBounds(10, 476, 447, 33);
    frame.getContentPane().add(textField);
    textField.setColumns(10);

    status = new JTextArea();
    status.setBounds(540, 250, 262, 215);
    frame.getContentPane().add(status);
    status.setEditable(false);

    JTextArea textArea_2 = new JTextArea();
    textArea_2.setBounds(540, 12, 262, 228);
    frame.getContentPane().add(textArea_2);

}

public void addText(String text){
    SimpleAttributeSet keyWord = new SimpleAttributeSet();
    try {
        int len = doc.getLength();
        doc.insertString(len, text + "\n", keyWord);
        formatColour(text, len);
    } catch (BadLocationException e) {
        e.printStackTrace();
    }
}

public void formatColour(String text, int offset){
    System.out.println("Text: " + text + " length + " + text.length() + " offset is: " + offset);
    int before = offset;
    if (before < 0) before = 0;
    int after = text.length();
    int wordL = before;
    int wordR = before;

    while (wordR < after) {
        /*boolean is = true;
        if (wordR == after || is) {*/
       try{
            System.out.println("Now looking at:" + text.substring(wordL, wordR) + " wordR is: " + wordR + " and offset is: " + offset + " worldL is: " + wordL);
          if(text.substring(wordL, wordR).matches("§") && text.length() >= (wordR+1-offset)){
            if (text.substring(wordL, wordR+1).contains("0")){
                doc.setCharacterAttributes(wordL, text.length(), black, false);
                doc.remove(wordL, 2);
            }else if(text.substring(wordL, wordR+1).contains("1")){
                doc.setCharacterAttributes(wordL, text.length(), blue, false);
                doc.remove(wordL, 2);
            }else if(text.substring(wordL, wordR+1).contains("2")){                        
                doc.setCharacterAttributes(wordL, text.length(), green, false);
                doc.remove(wordL, 2);
            }else if(text.substring(wordL, wordR+1).contains("3")){
                doc.setCharacterAttributes(wordL, text.length(), dark_aqua, false);
                doc.remove(wordL, 2);
            }else if(text.substring(wordL, wordR+1).contains("4")){
                doc.setCharacterAttributes(wordL, text.length(), dark_red, false);
                doc.remove(wordL, 2);
            }else if(text.substring(wordL, wordR+1).contains("5")){
                doc.setCharacterAttributes(wordL, text.length(), purple, false);
                doc.remove(wordL, 2);
            }else if(text.substring(wordL, wordR+1).contains("6")){
                doc.setCharacterAttributes(wordL, text.length(), orange, false);
                doc.remove(wordL, 2);
            }else if(text.substring(wordL, wordR+1).contains("7")){
                doc.setCharacterAttributes(wordL, text.length(), grey, false);
                doc.remove(wordL, 2);
            }else if(text.substring(wordL, wordR+1).contains("8")){
                doc.setCharacterAttributes(wordL, text.length(), dark_grey, false);
                doc.remove(wordL, 2);
            }else if(text.substring(wordL, wordR+1).contains("9")){
                doc.setCharacterAttributes(wordL, text.length(), indigo, false);
                doc.remove(wordL, 2);
            }else if(text.substring(wordL, wordR+1).contains("a")){
                doc.setCharacterAttributes(wordL, text.length(), bright_green, false);
                doc.remove(wordL, 2);
            }else if(text.substring(wordL, wordR+1).contains("b")){
                doc.setCharacterAttributes(wordL, text.length(), aqua, false);
                doc.remove(wordL, 2);
            }else if(text.substring(wordL, wordR+1).contains("c")){
                doc.setCharacterAttributes(wordL, text.length(), red, false);
                doc.remove(wordL, 2);
            }else if(text.substring(wordL, wordR+1).contains("d")){
                doc.setCharacterAttributes(wordL, text.length(), pink, false);
                doc.remove(wordL, 2);
            }else if(text.substring(wordL, wordR+1).contains("e")){
                doc.setCharacterAttributes(wordL, text.length(), yellow, false);
                doc.remove(wordL, 2);
            }else if(text.substring(wordL, wordR+1).contains("f")){
                doc.setCharacterAttributes(wordL, text.length(), white, false);
                doc.remove(wordL, 2);
            }else if(text.substring(wordL, wordR+1).contains("r")){
                doc.setCharacterAttributes(wordL, text.length(), reset, false);
                doc.remove(wordL, 2);
            }else{
                doc.setCharacterAttributes(wordL, wordR - wordL, attrBlack, false);
                doc.remove(wordL, 1);
            }            
        }
      wordL = wordR;  
      wordR++;
     } catch (BadLocationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
  }
}
导入java.awt.Color;
导入java.awt.Graphics;
导入java.awt.Graphics2D;
导入java.awt.Label;
导入javax.swing.JFrame;
导入java.awt.geom.Ellipse2D;
导入javax.swing.JPanel;
导入javax.swing.JTextArea;
导入javax.swing.JTextField;
导入javax.swing.JButton;
导入java.awt.event.ActionListener;
导入java.awt.event.ActionEvent;
导入java.io.IOException;
导入java.util.Timer;
导入java.util.TimerTask;
导入javax.swing.JLabel;
导入javax.swing.JScrollPane;
导入me.woder.bot.Client;
导入javax.swing.JTextPane;
导入javax.swing.text.AttributeSet;
导入javax.swing.text.BadLocationException;
导入javax.swing.text.DefaultStyledDocument;
导入javax.swing.text.SimpleAttributeSet;
导入javax.swing.text.StyleConstants;
导入javax.swing.text.StyleContext;
公共类TorchGUI扩展了JPanel{
私有静态最终长serialVersionUID=1L;
公共框架;
私有JTextField textField;
客户c;
JTextPane聊天;
区域状况;
final StyleContext cont=StyleContext.getDefaultStyleContext();
最终属性set black=cont.addAttribute(cont.getEmptySet(),StyleConstants.Foreground,新颜色(0,0,0));
最终属性set blue=cont.addAttribute(cont.getEmptySet(),StyleConstants.前台,新颜色(0,0170));
最终属性set green=cont.addAttribute(cont.getEmptySet(),StyleConstants.Foreground,新颜色(0170,0));
最终属性set dark_aqua=cont.addAttribute(cont.getEmptySet(),StyleConstants.Foreground,新颜色(0170170));
最终属性设置深红色=cont.addAttribute(cont.getEmptySet(),StyleConstants.前台,新颜色(170,0,0));
最终属性set purple=cont.addAttribute(cont.getEmptySet(),StyleConstants.前台,新颜色(170,0170));
最终属性set orange=cont.addAttribute(cont.getEmptySet(),StyleConstants.Foreground,新颜色(255170,0));
最终属性set grey=cont.addAttribute(cont.getEmptySet(),StyleConstants.Foreground,新颜色(170170));
最终属性集深灰色=cont.addAttribute(cont.getEmptySet(),StyleConstants.前台,新颜色(85,85,85));
最终属性set indigo=cont.addAttribute(cont.getEmptySet(),StyleConstants.前台,新颜色(85,85255));
最终属性set bright_green=cont.addAttribute(cont.getEmptySet(),StyleConstants.Foreground,新颜色(85255,85));
最终属性set aqua=cont.addAttribute(cont.getEmptySet(),StyleConstants.前台,新颜色(85255255));
最终属性set red=cont.addAttribute(cont.getEmptySet(),StyleConstants.前台,新颜色(255,85,85));
最终属性set pink=cont.addAttribute(cont.getEmptySet(),StyleConstants.前台,新颜色(255,85255));
final AttributeSet yellow=cont.addAttribute(cont.getEmptySet(),StyleConstants.前台,新颜色(255255,85));
最终属性set white=cont.addAttribute(cont.getEmptySet(),StyleConstants.前台,新颜色(255255));
最终属性集重置=cont.addAttribute(cont.getEmptySet(),StyleConstants.Foreground,Color.black);
最终属性set attrBlack=cont.addAttribute(cont.getEmptySet(),StyleConstants.Foreground,Color.BLACK);
DefaultStyledDocument doc=新的DefaultStyledDocument(){
私有静态最终长serialVersionUID=1L;
};
/**启动它
* 
*/公共静态void main(字符串[]args){
TorchGUI窗口;
window=新的TorchGUI();
window.frame.setVisible(true);
window.addText(§0这应该是黑色的§1这应该是蓝色的);
}
/**
*创建应用程序。
*/
公共火炬GUI(/*客户端c*/){
//这个.c=c;
初始化();
}
/**
*初始化框架的内容。
*/
私有void初始化(){
框架=新JFrame(“火炬手2.1”);
框架.立根(100100944555);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JScrollPane scrollPane=新的JScrollPane();
滚动窗格.立根(10,11,520,454);
frame.getContentPane().add(滚动窗格);
chat=新的JTextPane(文档);
scrollPane.setViewportView(聊天);
chat.setEditable(false);
textField=新的JTextField();
textField.setBounds(10476447433);
frame.getContentPane().add(textField);
textField.setColumns(10);
状态=新的JTextArea();
地位.挫折(540250262215);
frame.getContentPane().add(状态);
status.setEditable(false);
JTextArea textArea_2=新的JTextArea();
text区域_2.立根(540、12、262、228);
frame.getContentPane().add(textArea_2);
}
公共无效添加文本(字符串文本){
SimpleAttributeSet关键字=新建SimpleAttributeSet();
试一试{
int len=doc.getLength();
doc.insertString(len,text+“\n”,关键字);
格式颜色(文本,len);
}捕获(错误位置异常e){
e、 printStackTrace();
}
}
公共空白格式颜色(字符串文本,整数偏移){
System.out.println(“文本:“+Text+”长度+“+Text.length()+”偏移量为:“+offset”);
int before=偏移量;
如果(之前<0)之前=0;
int after=text.length();
int-wordL=before;
int-wordR=before;
while(wordRpublic void addText(String text)
{
    HashMap<String, AttributeSet> attributes = new HashMap<String, AttributeSet>();
    attributes.put("0", black);
    attributes.put("1", blue);

    String[] lines = text.split("%");

    for (int i = 1; i < lines.length; i++)
    {
        String line = lines[i];
        String key = line.substring(0, 1);
        String theText = line.substring(1);
        AttributeSet attribute = attributes.get(key);

        try
        {
            int len = doc.getLength();
            doc.insertString(len, theText, attribute);
        }
        catch (BadLocationException e)
        {
            e.printStackTrace();
        }
    }
}