6

我可以改变颜色的一种方法是通过 setForground()。但是,当有多行代码时,它会使所有内容变为绿色或黑色。是否有另一种方法或任何方法来解决这个问题?谢谢!

int key = evt.getKeyCode();
    if (key == KeyEvent.VK_ENTER)
    {
       String tb1EnterdValue = tb1.getText().toString();
       if((tb1EnterdValue.equals("yes")) )
        {
            TextArea1.setForeground(Color.green);
    else
        {
              TextArea1.setForeground(Color.lightGray);
        }
       this.TextArea1.append(">"+tb1EnterdValue+newline);
       this.tb1.setText("");
4

2 回答 2

3

I would use a JTextPane with "attributes" (not HTML) for changing the text color. The section from the Swing tutorial on Text Component Features has a working examples to get you started.

I've tried JTextPanes before but they won't let me use append() method

The append() method is just a convenience method that allows you to add text to the end of the Document. You can implement you own append() method for a JTextPane as well. Just look at the source code for JTextArea and copy the code from its append() method.

于 2011-01-11T04:09:32.000 回答
0

这是 Swing 吗?您使用的是 JTextAreas 吗?如果是这样,请具体说明您的问题,然后不要使用 JTextArea,因为如果您想在一个文本组件中使用多种格式,它不是理想的文本组件。而是考虑使用 JTextPane 或 JEditorPane。这些教程将向您展示如何使用它们以及何时使用它们。

于 2011-01-11T03:51:49.263 回答