有没有办法突出显示或更改从String []添加到JTextArea的字符串的颜色?
目前,我正在将DefaultHighlighter与addHighlighter(from,to,Highlighter)方法一起使用,但是这种方式不起作用。
String []来自记录按键输入的列表,并且'希望将每个单个字符的字符串突出显示为彩色。
JTextArea的示例如下:A B C D E F G [SPACE] H I J K L [ENTER]。
顺便说一句,我一次用一个for循环将一个字符串添加到textArea:
for(int cnt = 0; cnt <= strings.length; cnt++){
if(strings[cnt].length() != 1){
text.append("[" + strings[cnt] + "] ");
}
else{
text.append(strings[cnt]);
//tryed to do it like that, but obviously did not work the way it wanted it to
// text.getHighlighter()。addHighlight(cnt,cnt + 1,highlightPainter);
}
}
最佳答案
JTextArea
的颜色适用于整个JTextComponent's
Document
文本前景色,而不适用于单个字符。您可以改用JTextPane
这是一个简单的示例:
public class ColoredTextApp {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Colored Text");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
StyledDocument doc = new DefaultStyledDocument();
JTextPane textPane = new JTextPane(doc);
textPane.setText("Different Colored Text");
Random random = new Random();
for (int i = 0; i < textPane.getDocument().getLength(); i++) {
SimpleAttributeSet set = new SimpleAttributeSet();
StyleConstants.setForeground(set,
new Color(random.nextInt(256), random.nextInt(256),
random.nextInt(256)));
StyleConstants.setFontSize(set, random.nextInt(12) + 12);
StyleConstants.setBold(set, random.nextBoolean());
doc.setCharacterAttributes(i, 1, set, true);
}
frame.add(new JScrollPane(textPane));
frame.pack();
frame.setVisible(true);
}
});
}
}