Java - Swing setting colour to text in JTextArea - java

I have a JTextArea which has its text set to a string of information. In this string of information I have a variable which I would like coloured red, to do this I edit the string as follows:
"Result: <html><font color=red>" + negativeValue + "</font></html>"
I would expect this to give Result: ## where the number is red. However it just puts the following into the text area:
Result: <html><font color=red>##</font></html>
I'm not really sure how to get this working, so could someone offer advice as to how to do so?

JTextArea is not a component designed for styled text. If the text can be all one color, call setForeground(Color).
Otherwise use a styled text component such as a JEditorPane or JTextPane. For more info. on using them, see How to Use Editor Panes and Text Panes.
Also as pointed out by others, the entire String must start with <html> .

You cannot use HTML in a JTextArea, but you can use it with a JEditorPane

JTextArea doesn't support styled text area, in order to render HTML you need an instance of JEditorPane or JTextPane. See the tutorial on Using Text Components
.
Sample code here

If memory serves, JTextArea is for plain text display only. For HTML, you must use JEditorPane or one of its subclasses.

Java renders html code only if it starts with <html>. You should try it like
"<html>Result: <font color=red>" + negativeValue + "</font></html>"

Related

Programmatically detect if Swing HTML markup rendered correctly

Is there a way to detect if a (synthatically correct) HTML rendered in a JLabel has rendered succesfully, and is displaying all intended Glyph(s)
I have the following HTML String:
<html><h3>Title</h3><ul><li><b>S</b>tuff</li><li><b>S</b>taff</li><li><b>S</b>tiff</li></ul></html>
That renders:
TitleStuffStaffStiff
However, in an application, the same HTML inside a JLabel rendered as:
As it can be seen, nothing is bold, my custom HTML parser can check for HTML issues, and it detects that String as correct, it then parses "correctly", and renders the Glyph(s), however, the bold Glyph(s) are being replaced by their default plain Glyph(s).
Is there a way to programatically detect that the Glyph was not used, and search for the Glyph, and replace it?
Also worth noticing:
Similar question(s) have not yielded significant result(s). I can confirm that the HTML is always correct, and even using the "test HTML", the issue occurred.The Font contains the bold faceOther HTML markup is being rendered correctly elsewhere(p, i, h, etc.)The HTML is from other supplier(s), and should not be altered/handled/defined
JLabel text by default is already bold. You cannot double bold it, you can only unbold it and rebold it.
Try:
<html><body style="font-weight: normal"><h3>Title</h3><ul><li><b>S</b>tuff</li><li><b>S</b>taff</li><li><b>S</b>tiff</li></ul></body></html>

How to read an image from text pane?

Say a plain text and an image are entered by a user into a text pane. How to separately read the text and the image from such text pane?
If you have HTMLEditorKit set as the default editor kit, then get all the elements of the document. Then iterate through those elements and look for image element. Then separate them from the text elements. Following links may come to your help:
Element to string in HTMLDocument
How to get current html element(tag) in JTextPane?
To get the plain text from a JTextPane, you can use:
myJTextPane.getDocument().getText(...)
To get the image, you need to use StyleConstants.getIcon(...). For instance, to get the image at offset i:
StyleConstants.getIcon(((DefaultStyledDocument)myJTextPane.getDocument()).getCharacterElement(i).getAttributes()))

JEditorPane in html mode cuts last empty space when using setText

I have set my JEditorPane to use the text/html kit. If I try to setText("hey ") for example (note the space after 'hey'), the editor pane displays just "hey", there is no space after. Does somebody know how I can solve this?
Why are you worried about this?
If you want simple unformatted text to be displayed, then use a JTextArea or JTextPane.
A JEditorPane is used to "format" text so it will parse the data and may remove unwanted characters.
If you want to force a space when using HTML then you can use:
editor.setText("hello&nbsp");

Making words different colors in JTextField/JTextPane/?

I'm trying and failing to understand how to use Java's text editor components to colorize text as you insert it. I don't want or need a fully featured syntax highlighting library.
Basically, I have a JTextField (or some other JText... component), and a list of words. I want any words in the field that appear in the list to be red, and the rest of the words be green. So for example, if "fire" is in the list, "fir" would appear green and "fire" would appear red.
I've tried using a JTextPane and a DefaultStyledDocument, using a KeyListener to go over the text in the document and using AbstractStyledDocument.replace to replace the existing words with versions that have the correct attributes. This didn't do anything. What am I doing wrong?
Neither JTextPane nor JTextField isn't able to present formatted text, i.e text having more than one format. For text-editor-like capabilities like you'd find in WordPad or HTML, the component to use is the JEditorPane or its descendant, JTextPane.
The simplest thing you can do is set the ContentType of the JEditorPane to "text/html" and simply set its text to a string containing HTML. The Java structured text components are surprisingly competent with HTML; you can display tables and/or DIVs, and there is support for much of CSS2. Simplest to do your styles inline, but you can even do external style hrefs.
If you want to get fancy programmatically, you can access the DocumentModel and create text from spans of text each having their own formatting. The DocumentModel works essentially like a programmable text editor.
EDIT: Re-reading your question, I see my answer doesn't quite address it. Since you want multi-colored text JEditorPane is your only option; but rather than just piping in pre-colored text via HTML or such, you'll have to put a listener on your document model to catch changes introduced when you type; and after every document change you'll want to examine the text (again from the Document model) for text that should or should not be highlighted, and you'll want to apply formatting to certain runs of text.
There are devils in the details, but this should get you started.

Java JEditorPane Format

im trying to implement a Chat feature in my application. i have used 2 JEditorPane. one for holding chat history and the other for sending chat to the previous JEditorPane.
the JEditorPane is text/html type.
the problem i am having is when i put more than one space between characters it is automatically removed by the parser because it is HTML!
how can i make it so, that the spaces are not stripped?
example: hello world
becomes: hello world
also i am having to parse the html tags so the new messages 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 boxes/panes to be able to handle bold, URL embedding for now.
thank you and look forward to your guidance.
EDIT: im trying to replace " " with a relavent char.
newHome[1] = newHome[1].replace(" ", newChar)
what should be the newChar value?
EDIT: im trying:
newHome[1] = newHome[1].replaceAll(" ", " ");
but it is not producing the results. any ideas?
EDIT: #Thomas - thanks! for some reason i can post a note to your answer.
Using HTML markup is a quick way to get simple text formatting done in a Swing text component. However, it's not the only way.
A more sophisticated method is to use a javax.swing.text.StyledDocument to which you can attach different "styles" (hence the name). A style is basically a set of attributes, for instance, whether the text should be in bold or italics or what Color it should have.
JTextPane provides a number of convenience methods to deal with styles, and it is a subclass of JEditorPane which means it should integrate rather seamlessly into your existing code. As an example, to mark a portion of the text within a JTextPane as bold, you could 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);
Similarly, you could define a second style that e.g. uses a blue, underlined font and which you could use to display hyperlinks.
Unfortunately, the downside is that you will have to take care of the mechanics of the links yourself. Although you can use the existing infrastructure of javax.swing.event.HyperlinkListener et al., you will be responsible for detecting mouse clicks. The same goes for hovering and changing the Cursor into a hand-symbol etc.

Categories