I have this statement:
s = s + "Id: " + lc.getID() + " Name: " + lc.getName() + "\n"
+ " Phone Number: " + lc.getPhone() + " Email: " + lc.getEmail() + "\n"
+ " Description: " + lc.getDescription() + "\n\n"
that prints this out:
Id: 1 Name: Eric
Phone Number: 8294038 Email: foo#gmail.com
Description: Cool guy Eric
I want to Bold only the titles (Id, Name, etc).
I tried this:
s = s + Html.fromHtml(" <b> Id: </b>" + lc.getID() + " <b> Name: </b>" + lc.getName() + "\n"
+ " Phone Number: " + lc.getPhone() + " Email: " + lc.getEmail() + "\n"
+ " Description: " + lc.getDescription() + "\n"
+ "\n\n");
But not only does it not bold, but it takes away the new lines (\n). Any ideas on how to get this done? Thanks.
Html.fromHtml() returns a Spanned object, designed to be put directly into a TextView or similar widget.
A Spanned is not a String.
By doing s = s + Html.fromHtml(...), you are saying "please parse this HTML into a Spanned, then throw out all the formatting to give me a String that I can concatenate onto some other String". That's not what you want -- you want to keep the formatting. But a Java String does not have formatting, and so ordinary string concatenation has no way to keep it.
Beyond that, as Manishika pointed out, newlines are ignored in HTML anyway, as you use HTML elements for vertical whitespace.
Your options include:
Generate a complete HTML snippet -- including whatever it is you are trying to concatenate it to -- and then use Html.fromHtml() on the entire thing. You may wish to use a template engine (e.g., jmustache) for that, or String.format(). Or, use StringBuilder, rather than lots of + operations (less memory churn, faster performance). Be sure to use <br/> or <p> for your line breaks/paragraph delimiters.
Use SpannableStringBuilder to assemble the string and its formatting from component parts.
Use TextUtils.concat(s, Html.fromHtml(...)) instead of s + Html.fromHtml(...), as concat() will maintain the spans that implement the formatting. While the implementation of Spanned returned by fromHtml() is not a String, both it and String are a CharSequence, and hence work with concat().
It will require a little bit of parsing on your end, but you definitely want to look into SpannableStrings.
For example, let's say I have the following string:
String s = "How now brown cow";
I would then turn it into a SpannableString by simply feeding the string to the constructor as follows:
SpannableString ss = new SpannableString(s);
From there you need your stylization with the spanned area. For this, I'll just use SubscriptSpan, though if you wish to make your own you can simply make your own class extending CharacterStyle and override the updateDrawState(TextPaint ds) method. The following is how you can set you span:
/ *
* the first argument is the span effect you want, the second and third
* are the start and end indices, respectively, and the last argument is
* for setting a flag, which you probably won't need.
*/
ss.setSpan(new SubscriptSpan(), 0, 2, 0);
And now you can just put your string straight into the TextView and it should appear how you want, like so:
myTextView.setText(ss);
Related
In my custom GET endpoint, I would like to return a String but, to "beautify" it, I would like to insert new line for each different information. I've tried with \n\r this way
return "Name of process definition: "+ obj.getString("processDefinitionName") + "\r\n" + "Start time of instance: " + obj.getString("startTime")
+ "||" + "End time of the instance: " + obj.getString("endTime") + "||" + "Total duration time(ms): " + obj.getInt("durationInMillis");
but it only prints a white space and the text is written on the same line. Why is it not working?
You have to use HTML tags to display new line on browser. You can use <br/> tag to add new line. Browser parses your response in HTML form.
I want the "Module Code = " and "Result = " to be separated by a tab but whenever I run the code below it literally just outputs
"Module Code = Biology\tResult = 40.0"
public String toString()
{
return "Module Code = " + moduleCode + "\t" + "Result = " + result;
}
The problem is that you're viewing the value of the produced string in the BlueJ window. That window is good for debugging purposes, but it won't exhibit the same behavior that a proper output device would, especially with respect to characters such as newline, tabulation, etc. Those characters will still appear with their escape sequences, just like you typed them in your source code.
In other words, your toString() method is fine and it works as intended. If you want to see its results formatted properly, don't view them using BlueJ -- print them somewhere else. The console is a good choice:
System.out.println(module.toString());
Why won't “\t” create a new line?
well, that is because “\t” is a tabulation not a new line “\n”
if you need a new line try instead
return "Module Code = " + moduleCode + "\n" + "Result = " + result;
How can I automatically print without poping up dialog box or automatically accept print dialog? Here is some of my code:
if ("OUT".equals(rs.getString("empattendance"))) {
String date = dft.format(dNow);
String time = tft.format(dNow);
textArea.setText(date + "\n" + "\n" +
fullname +"\n" +
"Time In: " + time + "\n" +
"Status: "+ statusin +
"\n" +
"\n" +
"____________________\n" +
" Sign by Supervisor");
try {
//printing
Boolean complete = textArea.print();
if(complete){
}
else{
}
} catch (PrinterException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
and here's the screenshot of the current behaviour.
thanks
When I look at your code I have few thoughts before answer.
1) Do not use String. Better for comparing stuff is Enumerators I believe.
2) If you would like to set text to textArea previously create some method using StringBuilder for example which will be creating the String you would like to set. Joshua Bloch says
Item 15: minimize mutability (...) If a client requires performing expensive multi-stage operations on your class, expose them as primitive methods, or provide a mutable companion class (like StringBuilder for String).
And take a look at this topic for more.
3) To print data from textArea if I were you I would try to use this.
I believe that would help you
I read, some StackOverflow questions that I need to use HTML stuffs.
But what would be the easiest it without any of HTML stuff.
Here's the code
label.setText(label.getText() + (String)boxTimes.getSelectedItem() + input);
This code will produce this
What I want is:
You must know a bit of basic String format:
\n line break
\t tab
So your code will be like:
String myLabel =
// 4
label.getText() + "\n\n" +
// 7:00
(String)boxTimes.getSelectedItem() + "\t" +
// - Going out....
"- " + input;
label.setText(myLabel);
But as long as JLabel does not accept \n as Abishek Manoharan pointed, you must use <br>.
String myLabel =
"<html>" +
label.getText() +
"<br/><br/>" +
(String)boxTimes.getSelectedItem() + " - " + input +
"</html>;
label.setText(myLabel);
I was faced with the same problem too and couldn't find a viable solution.
So I went ahead and used a JTextArea instead of JLabel.
JTextArea label = new JTextArea();
label.setEditable(false);
label.setBackground(null);
It gives the same look and feel of a JLabel
You can use '\n' and '\t' as you like,
and what more, the text is selectable which is not possible in JLabel.
I'm parsing some folder names here. I have a program that lists subfolders of a folder and parses folder names.
For example, one folder could be named something like this:
"Folder.Name.1234.Some.Info.Here-ToBeParsed"
and I would like to parse it so name would be "Folder Name". At the moment I'm first using string.replaceAll() to get rid of special characters and then there is this 4-digit sequence. I would like to split string on that point. How can I achieve this?
Currently my code looks something like this:
// Parsing string if regex p matches folder's name
if(b) {
//System.out.println("Folder: \" " + name + "\" contains special characters.");
String result = name.replaceAll("[\\p{P}\\p{S}]", " "); // Getting rid of all punctuations and symbols.
//System.out.println("Parsed: " + name + " > " + result);
// If string matches regex p2
if(b2) {
//System.out.println("Folder: \" " + result + "\" contains release year.");
String parsed_name[] = result.split("20"); // This is the line i would like to split when 4-digits in row occur.
//System.out.println("Parsed: " + result + " > " + parsed_name[0]);
movieNames.add(parsed_name[0]);
}
Or maybe there is even easier way to do this? Thanks in advance!
You should keep it simple like this:
String name = "Folder.Name.1234.Some.Info.Here-ToBeParsed";
String repl = name.replaceFirst( "\\.\\d{4}.*", "" ).
replaceAll( "[\\p{P}\\p{S}&&[^']]+", " " );
//=> Folder Name
replaceFirst is removing everything after a DOT and 4 digits
replaceAll is replacing all punctuation and space (except apostrophe) by a single space