java 打印输出格式类封装

控制台可以输出多种字体样式,前景色和背景色,与语言无关。

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

测试效果
在这里插入图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值