我正在使用 Swing Jframe 表单在 java 中创建一个打字测试游戏。
在程序中,我正在比较文本字段(输入)和标签框(预定义示例)的字符。如果两者的字符相同,则标签框中该字符的颜色应变为绿色,否则为红色。
例如:标签框中的示例文本:这是示例
如果在文本字段框中输入的第一个字符是 T,则标签框中的“T”应变为绿色,否则变为红色。
我尝试过使用label.setForeground()
选项,它将整个文本变成该特定颜色。
我尝试过使用label.setText(String.format("<html> text1 <font color='red'> text2 </font></html>"));
选项,它仅将代码之间的文本转换为相应的颜色。
请指导我,如果有我应该知道的 html 功能或我应该使用的 java 功能来完成此任务。提前致谢。
最佳答案
the color of that character shall turn green in the label box otherwise red.
不要为此使用 JLabel(和 HTML)。
而是使用JTextPane
。您可以轻松更改单个角色的属性。
帮助您入门的简单示例:
JTextPane textPane = new JTextPane();
textPane.setText( "Hello" );
// Define some character attributes
SimpleAttributeSet green = new SimpleAttributeSet();
StyleConstants.setForeground(green, Color.GREEN);
// Change attributes on some existing text
StyledDocument doc = textPane.getStyledDocument();
doc.setCharacterAttributes(0, 1, green, false);
关于java - JAVA动态改变标签框中字符的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46478067/