在将字符串添加到JTextArea之前对其进行着色

时间:2013-08-13 17:54:16

标签: java string swing colors jtextarea

有没有办法,突出显示或更改从String []添加到JTextArea的字符串的颜色? 目前我正在使用带有addHighlighter(from,to,highlighter)方法的DefaultHighlighter,但这并不像'想要的那样'。 String []来自记录键输入的列表,并且'希望每个单字符串都被突出显示为彩色。

示例JTextArea的样子:A B C D E F G [SPACE] H I J K L [ENTER]。

顺便说一句,我一次向textArea添加一个字符串,其中包含一个for循环:

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);             }         }

2 个答案:

答案 0 :(得分:6)

JTextArea的颜色适用于整个 JTextComponent's Document文本前景色而不是单个字符。您可以使用JTextPane代替

这是一个简单的例子:

enter image description here

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);
            }
        });
    }
}

答案 1 :(得分:4)

你做不到。 JTextArea是明文无格式文本。所有文本都可以是相同的字体或前景色,但这就是它。您需要使用JTextPaneJEditorPane代替。

查看JTextPane / JEditorPane Tutorial

相关问题