Java 控制台中的颜色 [英] Colours in Java console

查看:23
本文介绍了Java 控制台中的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我想知道是否有任何方法可以在 Java 控制台应用程序中指定背景和文本的颜色.我正在写一个控制台菜单.另外,如果有任何简单的方法可以清除控制台.

basically, I was wondering if there is any way of specifying the colours of the background and text in a Java console application. I am writing a console menu. Also, if there is any easy way of clearing the console.

谢谢.

推荐答案

您可以使用 ANSI 转义码 为许多平台上的控制台应用程序指定文本的前景色和背景色,假设您用来运行应用程序的终端支持 ANSI 模式.您不需要任何额外的库来使用这些代码,您只需将它们直接嵌入到您的字符串中即可.但是,由于它们看起来有点乱,您可以使用诸如 JCurses 之类的库来制作它应用各种 ANSI 代码更容易一些.

You can use ANSI escape codes to specify the foreground and background colors of text for console apps on many platforms, assuming the terminal you're using to run the application supports ANSI mode. You don't need any additional libraries to use these codes, you can just embed them directly in your strings. However, since they're a bit messy looking, you can use a library such as JCurses to make it a bit easier to apply the various ANSI codes.

这是一个示例程序:

public static void main(String args[]) {
    System.out.println((char)27+"[01;31m;This text is red."+(char)27+"[00;00m");
    System.out.println((char)27+"[01;32m;This text is green."+(char)27+"[00;00m");
}

作为奖励,ANSI 转义码也将帮助您清除屏幕和光标定位.

As a bonus, ANSI escape codes will help you with screen clearing and cursors positioning, as well.

这篇关于Java 控制台中的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆