根据 JTextPane 中的颜色代码动态着色文本



我正在尝试使用StyledDocument制作一个文本窗格,当doc.insertString(doc.getLength(doc.getLength(),text + "",keyWord)时;它用颜色替换"§"的所有实例,然后是一个数字(所以像"§1"),并且应该删除代码本身并保留文本颜色。代码能够着色和删除,但问题是当我从实际文档(文本窗格)中删除文本时,我拥有的局部变量没有更新,我不确定最好的方法是什么(局部变量是"文本")。这样做的问题是它开始删除不是代码的东西,我认为这是由错误的索引引起的。

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();
    }
  }
}

}

感谢您的帮助。

我会在

将文本添加到文档之前对其进行解析。

您还希望摆脱 if/else 语句。每当你看到这样的结构时,你就知道你有设计问题。

这是我将使用的方法:

public 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();
        }
    }
}

我不会将所有颜色定义为常量,而是将属性放入地图中,这将作为初始化 GUI 的一部分完成,因为您不想每次调用 addText() 方法时都重建 Map。

另外,我更改了我的代码以搜索"%",因为我不知道另一个字符是什么,因此您需要将其更改回特殊分隔符。实际上,您应该定义一个常量变量来包含分隔符值。

最后,你不应该在你的GUI组件中使用setBounds()。Swing 旨在与布局管理器一起使用。

最新更新