Java JEditorPane format

im trying to implement a chat function in my application. I have used 2 JEditorPane. one for keeping chat history and another for sending chat to the previous JEditorPane.

JEditorPane is text / html type.

the problem I am running into is when I put more than one space between characters, which is automatically removed by the parser because it is HTML!

how can I do this so that the spaces are not separated?

example: hello               world

becomes: hello world

      

Also I need to parse the html tags so that new posts can be added to the history window.

Is there a better option than using JEditorPane? if i used JTextPane would it be easier to implement?

I would like the chat windows / panels to be able to handle bold, URL embedding for now.

Thank you and look forward to your guidance.

EDIT: im trying to replace "" with relavent char.

newHome[1] = newHome[1].replace(" ", newChar) 

      

what should be the value of newChar?

EDIT: im trying:

newHome[1] = newHome[1].replaceAll(" ", " ");

      

but it gives no results. any ideas?

EDIT: @Thomas - thanks! for some reason I may post a note for your answer.

+2


a source to share


1 answer


Using HTML markup is a quick way to easily format text in a Swing text component. However, this is not the only way.

A more sophisticated method is using javax.swing.text.StyledDocument

, to which you can attach different "styles" (hence the name). Style is basically a set of attributes, such as whether the text should be bold or italicized, or what color should it have.

JTextPane

provides a number of convenience methods for handling styles and is a subclass JEditorPane

, which means it should be easy to integrate into your existing code. As an example, to make a portion of the text inside the JTextPane bold, you can use something like this:



JTextPane textPane = new JTextPane();
Style bold = textPane.addStyle("bold", null);
StyleConstants.setBold(bold, true);

textPane.setText("I'll be bold.");

textPane.getStyledDocument().setCharacterAttributes(8, 4, bold, true);

      

Likewise, you can define a second style, for example, it uses a blue, underlined font and which you can use to display hyperlinks.

Unfortunately, the disadvantage is that you have to take care of the linking mechanism yourself. While you can use existing infrastructure javax.swing.event.HyperlinkListener

, etc., you will be responsible for detecting mouse clicks. The same applies to hovering and changing the cursor to a hand symbol, etc.

+3


a source







All Articles