开发者

Java: Is there any method in JTextPane that does the same thing as append() in JTextArea?

开发者 https://www.devze.com 2023-02-04 19:40 出处:网络
The program lets the user type in a command in a textfield then whatever they typed will show in the text area. If it is keywords such as yes it will turn green, however I cannot set just one line of

The program lets the user type in a command in a textfield then whatever they typed will show in the text area. If it is keywords such as yes it will turn green, however I cannot set just one line of text green in a text area so I need to use a text pane.

The problem is that if I use a text pane I can't use the append method anymore.

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);
      开发者_JAVA百科  }
    }


JTextPane uses Document as a model. This is necessary to support the use of multiple colors and fonts.
So, to append to a JTextPane, you need to modify the Document.
The following methods are available :

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

For example, this will append value to the end of the document.

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

Additionally, you may want to call scrollRectToVisible(Rectangle) with the result of modelToView(int) to ensure the newly added line is on screen.


I think you'll need to do that directly on the underlying document.

Something like this:

String value = textfield1.getText(); // no need for toString() here!
textPane.getDocument().insertString(textPane.getCaretPosition(), value, null);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号