JTextField with styled blocks - java

I need some kind of JTextField that replace carriage return characters by a styled block displaying the text <New Line> with another font, style or color.
By example, the text..
Dear Mr. Smith,\nblablabla...\nRegards...
..would be shown to the user, in a one line JTextField, this way :
Dear Mr. Smith,<New Line>blablabla...<New Line>Regards...
These <New Line> should be blocks that are selectable as if it was a single character and could be deleted with a single backspace. Pressing the return key would add a <New Line> at the caret position.
I think it can be possible by overriding PlainDocument, but I'm stuck in difficult to understand Document and EditorKit APIs. I would need some pointers about this one...
I do not have any objection using a JTextPane or JEditorPane as long as it behaves like a JTextField (one line, no scroll-bars).
Any suggestions?

Any suggestions ?
Use a JTextArea (a multi-line component) instead.
For an example, see this answer:
It would be simpler, but this is not what I have to do...
Fair enough, I missed the part that stated:
..with another font, style or color.
That would require a styled document such as JEditorPane or JTextPane.

Related

How can I create a new line in JTextField to type in?

I want to make a Swing program that writes updates on what you have done. It writes all the information on an uneditable JTextField.
For example:
You have changed the text to BLUE.
You have changed the text to RED.
The problem is that I can't make the two lines separate.
What I get is this:
You have changed the text to BLUE. You have changed the text to RED.
What I've tried is this: (This does not work)
TF_BetInfo.setText(TF_BetInfo.getText() + "\nYou have changed the text to BLUE.");
TF_BetInfo.setText(TF_BetInfo.getText() + "\nYou have changed the text to RED.");
you can't have multiple lines with JTextField , you can use JTextArea for that purpose , and the code wouldn't be much different too , you can still use the same code or you can just
TF_BetInfo.append("\nyou have ...... ");
where TF_Betinfo is a JTextArea rather than a JTextField .
You can't use JTextField for this. JTextField is sinle-line edit control. That is why you got all your output in one line.
If you want several lines to be printed in edit use JTextArea. In your case you can use jTextArea.append(string) (note: jTextArea is an object of class JTextArea, and string is an object of class String).
You can't actually use several lines in a JTextField, but what you can do, is using a JTextArea of the wanted size, and then use the following:
yourJTextArea.setLineWrap(true);
This will automatically detect when the JTextArea needs to use another line and add it, pretty cool, useful and you only need one code line to do it.
JTextArea is more flexible but if you really want flexibility read about JTextPane or JEditorPane, you can show URLS, internet pages and everything that comes to your mind.

JTextPane - dynamic word wrap

I tried to use jTextPane1.setText("xxx xxxx xxx xxxxx xx xxx xxxx xxx etc..."); but JTextPane does not word wrap it at all showing all the text in one line only instead.
It would be interesting to support word wrap on jTextPane1 resized too...
So my question is...
how to make JTextPane support word wrap?
Try using a JTextArea and call setWrapStyleWord(true); on its instance this should do what you need.
EDIT:
If you need to use a JTextPane as a requirement(which you said you do), then have a look at a similar question that I found which answer should be of help: How is word-wrapping implemented in JTextPane, and how do I make it wrap a string without spaces?
I had the same problem, the solution from David Kroukamp was very helpful. I changed it to JTextArea and set the following properties, as described in this tutorial:
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
Why not use a JTextArea instead of a Pane?
http://docs.oracle.com/javase/1.5.0/docs/api/
public void setWrapStyleWord(boolean word)
Sets the style of wrapping used if the text area is wrapping lines. If set to true the lines will be wrapped at word boundaries (whitespace) if they are too long to fit within the allocated width. If set to false, the lines will be wrapped at character boundaries. By default this property is false. Parameters: word - indicates if word boundaries should be used for line wrapping See Also: getWrapStyleWord()

Java - Swing setting colour to text in JTextArea

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>"

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