
本文介绍如何使用 Enigma 库的 TextAttributes 类为控制台输出的字符或字符串设置自定义颜色,通过传入 Color 实例实现高亮显示,适用于 Enigma 图形化控制台界面开发。
本文介绍如何使用 enigma 库的 `textattributes` 类为控制台输出的字符或字符串设置自定义颜色,通过传入 `color` 实例实现高亮显示,适用于 enigma 图形化控制台界面开发。
Enigma 是一个面向教学的 Java 控制台图形库,其 enigma.console.Console 提供了类似 DOS 窗口的字符级绘图能力。默认情况下,output(x, y, char) 方法以系统默认颜色(通常是白色/灰色)输出字符;若需增强视觉表现力(如错误提示用红色、关键信息用绿色),必须借助 TextAttributes 类显式指定文本样式。
✅ 正确设置颜色的三步流程
-
导入必要类
除基础 Enigma 类外,需显式引入 TextAttributes 和 java.awt.Color:import enigma.console.TextAttributes; import java.awt.Color;
-
创建带颜色的 TextAttributes 实例
TextAttributes 构造器接受一个 Color 对象作为前景色(背景色可选,见下文进阶用法):
Java Maven Common下载Java Maven 项目审查工作流的通用输入处理。当 Java Maven 项目以 ZIP压缩包或 GitLab 仓库 URL 形式提供且需要...时使用。
TextAttributes redAttr = new TextAttributes(Color.RED); TextAttributes greenAttr = new TextAttributes(Color.GREEN); TextAttributes blueAttr = new TextAttributes(Color.BLUE);
-
在 output() 中传入样式参数
使用重载方法 output(int x, int y, char c, TextAttributes attr) 或 output(int x, int y, String s, TextAttributes attr):cn.getTextWindow().output(10, 5, 'P', redAttr); // 单个红色字符 cn.getTextWindow().output(10, 6, "SUCCESS!", greenAttr); // 绿色字符串
⚠️ 注意事项与常见问题
- Color 类来源:务必使用 java.awt.Color(而非 javax.swing.Color 或自定义类),否则编译报错。
-
背景色支持:TextAttributes 也支持背景色,构造时可传入前景色 + 背景色:
TextAttributes highlight = new TextAttributes(Color.YELLOW, Color.BLACK); // 黄字黑底
-
性能提示:TextAttributes 实例可复用,无需为每个字符重复创建——建议声明为 final 常量:
private static final TextAttributes ERROR = new TextAttributes(Color.RED); private static final TextAttributes INFO = new TextAttributes(Color.CYAN);
- 兼容性说明:该方法仅适用于 Enigma 的图形化控制台窗口(如 "Mouse and Keyboard"),标准 System.out 不生效。
✅ 完整可运行示例
import enigma.core.Enigma;
import enigma.console.Console;
import enigma.console.TextAttributes;
import java.awt.Color;
public class ColoredConsoleDemo {
public static void main(String[] args) {
Console cn = Enigma.getConsole("Colored Demo");
// 定义常用样式
TextAttributes header = new TextAttributes(Color.MAGENTA);
TextAttributes value = new TextAttributes(Color.GREEN);
TextAttributes error = new TextAttributes(Color.RED);
// 输出带样式的文本
cn.getTextWindow().output(5, 2, "STATUS:", header);
cn.getTextWindow().output(5, 4, "OK", value);
cn.getTextWindow().output(5, 6, "ERROR: Invalid input", error);
}
}
掌握 TextAttributes 是提升 Enigma 控制台交互体验的关键一步。合理运用颜色不仅能提高信息辨识度,也使教学演示或调试过程更加直观高效。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










