控制台可以输出多种字体样式,前景色和背景色,与语言无关。
package com.shy;
/**
* 字体样式
*/
enum Style {
DEFAULT(0),HIGHLIGHT(1),NOTBOLD(22),UNDERLINE(4),NOTUNDERLINE(24),
BLINK(5),NOTBLINK(25),ANTIDISPLAY(7),NOTANTIDISPLAY(27);
private int value;
Style(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
/**
* 颜色类枚举,因为前景色和背景色相同颜色差值10,所以颜色用同一个枚举表示
*/
enum Color {
BLACK(30),RED(31),GREEN(32),YELLOW(33),
BLUE(34),PINK(35),AQUA(36),WHITE(37);
private int value;
Color(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
/**
* 打印到控制台时可以同时设置样式
*/
public class RichPrint {
private static String generateCmdContent(String content,Style style,Color foregroundColor,Color backgroundColor) {
String cmdContent = "\033[";
if(style != null) {
cmdContent += style.getValue()+";";
}
if (foregroundColor != null) {
cmdContent += foregroundColor.getValue()+";";
}
if (backgroundColor != null) {
cmdContent += backgroundColor.getValue() + 10;
}
cmdContent += "m" + content;
return cmdContent;
}
public static void print(String content,Style style,Color foregroundColor,Color backgroundColor) {
System.out.print(generateCmdContent(content,style,foregroundColor,backgroundColor));
}
public static void printLn(String content,Style style,Color foregroundColor,Color backgroundColor) {
System.out.println(generateCmdContent(content,style,foregroundColor,backgroundColor));
}
public static void printLnBlack(String content) {
printLn(content,null,Color.BLACK,null);
}
public static void printLnRed(String content) {
printLn(content,null,Color.RED,null);
}
public static void printLnGreen(String content) {
printLn(content,null,Color.GREEN,null);
}
public static void printLnYellow(String content) {
printLn(content,null,Color.YELLOW,null);
}
public static void printLnBlue(String content) {
printLn(content,null,Color.BLUE,null);
}
public static void printLnPink(String content) {
printLn(content,null,Color.PINK,null);
}
public static void printLnAqua(String content) {
printLn(content,null,Color.AQUA,null);
}
public static void printLnWhite(String content) {
printLn(content,null,Color.WHITE,null);
}
public static void main(String[] args) {
printLn("这是一段测试文本",Style.UNDERLINE, Color.AQUA,Color.PINK);
printLnYellow("测试文本2");
}
}
测试效果