【问题标题】:Java: Is there any method in JTextPane that does the same thing as append() in JTextArea?Java:JTextPane 中是否有任何方法与 JTextArea 中的 append() 执行相同的操作?
【发布时间】:2011-01-16 16:28:29
【问题描述】:

该程序允许用户在文本字段中输入命令,然后他们输入的任何内容都会显示在文本区域中。如果是yes之类的关键字,它会变成绿色,但是我不能在文本区域中只将一行文本设置为绿色,所以我需要使用文本窗格。

问题是,如果我使用文本窗格,我就不能再使用 append 方法了。

private final static String newline = "\n";
private void enterPressed(java.awt.event.KeyEvent evt) {                                      
    int key = evt.getKeyCode();
    if (key == KeyEvent.VK_ENTER)
    {
       String textfieldEnterdValue = textfield1.getText().toString();
       this.TextArea1.append("> "+tb1EnterdValue+newline);
       this.tb1.setText("");
       if((tb1EnterdValue.equals("yes")) )
        {
            TextArea1.setForeground(Color.green);
        }
    }

【问题讨论】:

    标签: swing netbeans-6.9 jtextfield jtextarea jtextpane


    【解决方案1】:

    JTextPane 使用Document 作为模型。这是支持使用多种颜色和字体所必需的。
    因此,要附加到 JTextPane,您需要修改 Document。
    可以使用以下方法:

    insertString(int pos, String value, AttributeSet att)
    remove(int pos, int length)

    例如,这会将value 附加到文档的末尾。

    Document d = textPane.getDocument();
    d.insertString(d.getLength(), value, null);
    

    此外,您可能希望使用modelToView(int) 的结果调用scrollRectToVisible(Rectangle),以确保新添加的行显示在屏幕上。

    【讨论】:

      【解决方案2】:

      我认为您需要直接在基础文档上执行此操作。

      类似这样的:

      字符串值 = textfield1.getText(); // 这里不需要 toString()! textPane.getDocument().insertString(textPane.getCaretPosition(), value, null);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-24
        • 2023-03-30
        • 1970-01-01
        • 2021-08-26
        • 2012-10-11
        • 1970-01-01
        • 2011-12-18
        • 1970-01-01
        相关资源
        最近更新 更多