【问题标题】:Coloring a string before adding it to a JTextArea在将字符串添加到 JTextArea 之前对其进行着色
【发布时间】:2013-08-15 11:21:52
【问题描述】:

有没有办法突出显示或更改从 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 是纯无格式文本。所有文本都可以是前景色,但仅此而已。您需要改用JTextPaneJEditorPane
  • 对于example :-)

标签: java string swing colors jtextarea


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    你不能。 JTextArea 是纯无格式文本。所有文本都可以是相同的字体或前景色,但仅此而已。您需要改用JTextPaneJEditorPane

    查看JTextPane / JEditorPane Tutorial

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 2017-07-15
      • 2015-02-18
      • 1970-01-01
      • 2010-11-22
      相关资源
      最近更新 更多