Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top