简体   繁体   中英

Neglect all escape characters and code JAVA

Situation:

  • I've got a string created like so

     \\033[32m\\033[44mP"+characterID+"\\033[0m" 
  • when the string is printed to console it prints out P + characterID in green like it should

Problem:

  • I need to create a label with the string P + characterID
  • But instead the text placed is [32m[44mP"+characterID+"[0m

What now:

  • Given that i have several strings with different colors, regex and replace doesn't seem to work for all.
  • is there anyway, i can neglect the escape codes and color when creating the text?

any suggestions?

If you are talking about Swing's JLabel or AWT - you can't use ANSI escape codes as you did in console. Instead you have to set the foreground or background color for that JLabel. Something like this:

JLabel label = new JLabel("P" + characterID);
label.setColor(Color.GREEN);

EDIT: If you already have "encoded" strings then you should come up with a regex that will find just the "real" data and ignore escape codes. Assuming you only have P , M and T prefixes and the characterID is a decimal number the regex should like this:

String realData = "\\033[32m\\033[44mP111\\033[0m".replace("[^PMT]\\d+", "");

This should remove everything but the data you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM