Question

I am setting up a JTextPane with chat like messages. I wanted to represent individual usernames as JLabel's. For an individual user, I wanted to use the identical JLabel object, so that any changes to that JLabel would propagate through all views of them in the same JTextPane. However, what I have found is that if the same object is inserted (insertComponent(...)), that the JTextPane erases the earlier one from whatever position it was at, and inserts at the current caret position. The first way around this would be to have individual JLabels for each and every username, but this could eventually lead to the creation of thousands of JLabels in the JTextPane.

I'm looking for any suggestions on a better way of going about this. The documentation does not cover this behavior it seems.

Was it helpful?

Solution

Any component has a parent component field, so evidently it can only be put in a view hierarchy once.

If you use a content type of the JTextPane styled text, like "text/html" you can insert images too. There is a swing demo with Alice in Wonderland providing low level image objects. In HTML one could add a <img src='...'> where the src either is a file:... or maybe some own protocol to get the image from the classpath (res:, resource: or classpath:). To write a protocol handler is not difficult, just a bit baroque.

Probably this answer suffices, which answers "JEditorPane with inline image."

OTHER TIPS

According to docs Each GUI component can be contained only once. because of you can only to create a new JLabel for each username.

Or you can use a JTextArea for your chat board, and add messages as a new lines of decorated name and text ot user.

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