Si vous utilisez Kotlin (qui fonctionne parfaitement avec Java), vous pouvez créer une telle énumération :
enum class AnsiColor(private val colorNumber: Byte) {
BLACK(0), RED(1), GREEN(2), YELLOW(3), BLUE(4), MAGENTA(5), CYAN(6), WHITE(7);
companion object {
private const val prefix = "\u001B"
const val RESET = "$prefix[0m"
private val isCompatible = "win" !in System.getProperty("os.name").toLowerCase()
}
val regular get() = if (isCompatible) "$prefix[0;3${colorNumber}m" else ""
val bold get() = if (isCompatible) "$prefix[1;3${colorNumber}m" else ""
val underline get() = if (isCompatible) "$prefix[4;3${colorNumber}m" else ""
val background get() = if (isCompatible) "$prefix[4${colorNumber}m" else ""
val highIntensity get() = if (isCompatible) "$prefix[0;9${colorNumber}m" else ""
val boldHighIntensity get() = if (isCompatible) "$prefix[1;9${colorNumber}m" else ""
val backgroundHighIntensity get() = if (isCompatible) "$prefix[0;10${colorNumber}m" else ""
}
Et ensuite l'utiliser comme ceci : (le code ci-dessous présente les différents styles pour toutes les couleurs)
val sampleText = "Ceci est un exemple de texte"
enumValues().forEach { ansiColor ->
println("${ansiColor.regular}$sampleText${AnsiColor.RESET}")
println("${ansiColor.bold}$sampleText${AnsiColor.RESET}")
println("${ansiColor.underline}$sampleText${AnsiColor.RESET}")
println("${ansiColor.background}$sampleText${AnsiColor.RESET}")
println("${ansiColor.highIntensity}$sampleText${AnsiColor.RESET}")
println("${ansiColor.boldHighIntensity}$sampleText${AnsiColor.RESET}")
println("${ansiColor.backgroundHighIntensity}$sampleText${AnsiColor.RESET}")
}
Si vous exécutez sur Windows où ces codes ANSI ne sont pas pris en charge, la vérification isCompatible
évite les problèmes en remplaçant les codes par une chaîne vide.
2 votes
Si la console prend en charge (par exemple, la console Java Eclipse) la personnalisation de la couleur de stdout/stderr, vous pouvez utiliser System.out.println pour une couleur et System.err.println pour une autre couleur.