JTextPane losing styling just after the text is displayed - java

I have a thread which functions as follows: characters are continuously entered, which are being stored in a StringBuilder. The contents of this string builder need to be styled according to some codes. As the character is appended in the string builder, I have a loop that splits this into an array of strings, and does some processing. Here is small (but complete in itself processing):
SimpleAttributeSet set = new SimpleAttributeSet();
if(string.contains(code1)){
str = string;
int index = string.indexOf(code1);
string = string.replaceAll(code1, "");
StyleConstants.setForeground(set, Color.GREEN);
// data is a another variable of string builder
data.append(string);
i = sb.indexOf(string);
String st = string.substring(index);
doc.setCharacterAttributes(data.indexOf(st), st.length(), set, true);
}
//similarly there are checks and styling for other codes
//terminalArea is of JTextPane type
terminalArea.setText(dataToShow.toString());
The text is colored correctly according to the codes, But as the data is displayed, the colors appear for an instant, and then lost. After that that, when a key is pressed, the colors appear again, but as the key is released, they lost.
I tried terminalArea.repaint(), but nothing happens.
Update:
With respect to StanislavL's answer, Here is what I am having now:
doc = new DefaultStyledDocument();
if(string.contains(code)){
str = string;
int index = string.indexOf(code);
string = string.replaceAll(code, "");
StyleConstants.setForeground(set, Color.GREEN);
dataToShow.append(string);
i = sb.indexOf(string);
String st = string.substring(index);
doc.setCharacterAttributes(dataToShow.indexOf(st), st.length(), set, true);
doc.insertString(doc.getLength() , string, null);
}
//after all conditions
terminalArea.setDocument(doc);
Though the color persists, but only that text is shown colored, which was colored last. The previous ones are shown in white.Please note, the whole string is not colored, only a part of it is colored.
Solved:
StanislavL's answer solved the problem. I overlooked this thing that I was setting the character attributes first, then inserting the array. Interchanging the position solved the issue.

I assume you use StyledEditorKit.
terminalArea.setText(dataToShow.toString());
The code just erases all you have and readd the text to the document. In fact in the document remove(0, docLength) is called and then insertString(theToStringResult) replaces all the styled.
I would recomment to create a new Document instance, insert all the texts with styled using insertString() where you can pass your attributes (or call insertString() just once and the call multiple times setCharacterAttributes()). After the Document instance is ready just call terminalArea.setDocument(theDocumentInstance); rather than setText();

Related

Setting the color of multiple characters of TextView in java

I will do my best to explain my problem, sorry if I am not clear. Basically I want to set the color of individual characters of a text, and then display them in Android App Development Kit. The problem I am having is that I am taking an array of the characters, and don't know how to set the color of them to a certain hexadecimal value.
For instance if the String is "hello". I would want each character to be a different color.
So I would take 'h' and assign it the hexadecimal value of "#000000". And then display it using xml. Is this possible? Here is what I am attempting to do now with my code.
String end = "";
for (int p = 0; p < charzart.size(); p++) {
if (charzart.get(p).equals(" ")) {
}
else{
Spannable colorSpan = new SpannableString(charzart.get(p));
int fake = Integer.parseInt(color.get(p));
colorSpan.setSpan(new ForegroundColorSpan(fake), 0, 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
end += colorSpan;
}
}
output.setText(end);
Right now my code doesn't work and I am not sure why. So i am running through charzart which holds my characters. And then attempting to assign the hexadecimal value ( which I have in another array list called color). I check to see if there is a space, if there is I ignore it and move on until i reach a character. From there, I get the character, set it to a spannable. I then get the color, apply it to the spannable, add it to a string and at the end set the TextView to that string.
Basically I want to know how to assign a hexadecimal value to a character, which will then be outputted by XML.

How do I add a list of user inputs into a textfield

Basically assume I have two text fields on my java applet:
[__________] [___________]
The first text field takes in user input and the second textbox prints that user input to store it as a list. So if the user inputted "cat" then "dog", then "frog", the second textfield should look like this:
[cat, dog, frog]. When the user types a word and clicks button 1 it should add the word into the second textfield. The code below is what I tried but nothing is happening:
textf = user input field
texty = output field
public void actionPerformed(ActionEvent e){
if (e.getSource() == b1 ){
x = textf.getText();
texty.add(x);
textf.setText(null);
}
Is this a Swing GUI? Are those JTextFields?
You need to look at the Java API since you're using an inappropriate method, add(...) in your code, and I'd be very surprised if your code with your use of the add method will even compile, since the add method is used for adding other GUI Components to the container that is calling the method, and that's not what you're trying to do.
You're trying to append text, and for that you will need to get the text from the 2nd text field, using getText() add the new String to this text using String concatenation (basically using the + operator, and then set the text of the 2nd text field with the new String using setText(...).
Myself, I'd display the accumulated texts in a JList or JTextArea and not a 2nd JTextField.
So if the user inputted "cat" then "dog", then "frog", the second textfield should look like this: [cat, dog, frog].
Then you need to insert the text into the Document of the text field:
So assuming you create the second JTextField with code like:
JTextField textField2 = new JTextField("[]");
You need to insert text before the "]". So you would insert the text into the Document of the second text field:
String text = textField1.getText() + ",";
Document doc = textField2.getDocument();
doc.insertString(text, doc.getLength() - 1, null);

how to replace a word with in contains() Method form a JtextPane

Well, I'm trying to replace a word by using contains() Method:
String z = tfB.getText().toString();
String show = textPane.getText().toString();
if(show.contains(z)){
// how I specify the word that were found and change it without
effecting anything with in that line
}
well what I main by that:
What I'm trying to do is get the value from the user.
then search if it found replace it with something. For example:
String x = "one two three four five";
It should set the textPane to "one two 3 four five"
or
"one two 3-three-3 four five"
could any one please tell me how to do it.
Thank you
What I'm trying to do is get the value from the user. then search if it found replace it with something.
Don't use the contains() method because you will need to search the text twice:
once to see if the text is found in the string
again to replace the text with a new string.
Instead, use the String.indexof(...) method. It will return the index of the text IF it is found in the String.
Then you should replace the text directly in the Document of the text pane, not in the String itself. So the code would be something like:
int length = textPane.getDocument().getLength();
String text = textPane.getDocument().getText(0, length);
String search = "abc...";
int offset = text.indexOf(search);
if (offset != -1)
{
textPane.setSelectionStart(offset);
textPane.setSelectionEnd(offset + search.length();
textPane.replaceSelection("123...");
}
Also, not that you get the text from the Document, not the text pane. This is to make sure the offsets are correct when you replace the text in the Document. Check out Text and New Lines for more information on why this is important.

Java PDFBox, extract data from a column of a table

I would like to find out how to extract from this pdf(ex. image) http://postimg.org/image/ypebht5dx/
For example, I want to extract only the values ​​in the column "TENSIONE[V]" and if it encounters a blank cell I enter the letter "X" in the output.
How could I do?
The code I used is this:
PDDocument p=PDDocument.load(new File("a.pdf"));
PDFTextStripper t=new PDFTextStripper();
System.out.println(t.getText(p));
and I get this output:
http://s23.postimg.org/wbhcrw03v/Immagine.png
These are just guidelines. Use them upon your use. This is not tested either, but help you solve your issue. If you have any question let me know.
String text = t.getText(p);
String lines[] = text.split("\\r?\\n"); // give you all the lines separated by new line
String cols[] = lines[0].split("\\s+") // gives array separated by whitespaces
// cols[0] contains pins
// clos[1] contains TENSIONE[V]
// cols[2] contains TOLLRENZA if not present then its empty

GWT: Putting raw HTML inside a Label

Is there a way to put raw HTML inside of a Label widget with GWT? The constructor and setText() methods automatically escape the text for HTML (so < appears as <, etc).
What I need is something like:
String matched = "two";
List<String> values = Arrays.asList("one", "two", "three");
StringBuilder sb = new StringBuilder();
for (String v : values){
if (v.equals(matched)){
sb.append("<b>" + v + "<b>");
} else {
sb.append(v);
}
sb.append(", ");
}
Label label = new Label();
label.setRawText(sb.toString());
//div contains the following HTML: "one, <b>two</b>, three, "
I want to output a comma-separated list of Strings, but I want one of those Strings to be bolded. Thanks.
Use the HTML class (Or more likely: The InlineHTML class instead of the Label class. InlineHTML works like label, except that you can give it html.
And just a security warning: if part of the input to your InlineHTML object is input by the user, remember to strip html out of that part, so users can't insert their own scripts into your code.
Sorry, I'm going to answer my own question because I found what I was looking for.
The SafeHtmlBuilder class is perfect for this. You tell it what strings you want to escape and what strings you do not want to escape. It works like StringBuilder because you call append methods:
String matched = "two";
List<String> values = Arrays.asList("one", "two", "three <escape-me>");
SafeHtmlBuilder builder = new SafeHtmlBuilder();
for (String v : values){
if (v.equals(matched)){
builder.appendHtmlConstant("<b>");
builder.appendEscaped(v);
builder.appendHtmlConstant("</b>");
} else {
builder.appendEscaped(v);
}
builder.appendEscaped(", ");
}
HTML widget = new HTML();
widget.setHTML(builder.toSafeHtml());
//div contains the following HTML: "one, <b>two</b>, three <escape-me>, "
Note that the appendHtmlConstant method expects a complete tag. So if you want to add attributes to the tag whose values change during runtime, it won't work. For example, this won't work (it throws an IllegalArgumentException):
String url = //...
SafeHtmlBuilder builder = new SafeHtmlBuilder();
builder.appendHtmlConstant("<a href=\""); //throws IllegalArgumentException
builder.appendEscaped(url);
builder.appendHtmlConstant("\">link</a>");
Either create a label and set it to bold:
Label label = new Label("text");
label.getElement().getStyle().setFontWeight(FontWeight.BOLD);
Or you can create a SpanElement and set its innerHtml.
Here's example to put a space in a widget, e.g. Label:
public void setTextNbsp( final Widget w ) {
w.getElement().setInnerHTML( " " );
}
Other HTML entities could be used as well. Take care with this not to open security holes. SafeHtml, etc. might need consideration if doing something more dynamic.
I think you should use SpanElement where you don't want the html to be escaped and label where you want then to be escaped and put them on a vertical panel so that they would appear as a single line of text.

Categories