views:

23

answers:

1

Hello, I'm working on a project that needs to be able to have JComponents inserted into a JTextPane, along with normal text. Currently, I'm using JTextPane.insertComponent(Component) to add the JComponents, however, they seem to be added sporadically with no real organization. I finally figured out that it's inserting it wherever the carat is located, so I tried setting it at the end of the text. However when I perform:

int len = txtConsole.getText().length();
txtConsole.setCaretPosition(len - 1);

I get an error saying that the location is invalid. Is there an easy, or better way to insert JComponents into the end of the JTextPane's last line?

Also, if the above is possible, is there a way to change where the JComponent is located inline with the rest of the text, such as centered inline?

+1  A: 

The following code works for me:

int offset = textPane.getDocument().getLength();
textPane.setCaretPosition(offset);
textPane.insertComponent( ... );

Make sure your code is executed on the EDT.

If you have further problems then post your SSCCE demonstrating the problem.

camickr
Sadly, http://sscce.org/ seems unresponsive recently; http://pscode.org/sscce.html is an alternative.
trashgod
That seems to work, Thanks.
404 Not Found
@trashgod, thanks.
camickr
Oops, spoke too soon: http://groups.google.com/group/comp.lang.java.programmer/browse_frm/thread/6e485775980cda2d
trashgod