I have a TextArea that has some prompt text that I want to be split onto a few different lines, however, line breaks don't work in prompt text for some reason.
Code:
TextArea paragraph = new TextArea();
paragraph.setWrapText(true);
paragraph.setPromptText(
"Stuff done today:\n"
+ "\n"
+ "- Went to the grocery store\n"
+ "- Ate some cookies\n"
+ "- Watched a tv show"
);
Result:
As you can see, the text does not line break properly. Does anyone know how to fix this?
The prompt is internally shown by a node of type Text which can handle line breaks. So the interesting question is why don't they show? Reason is revealed by looking at the promptText property: it is silently replacing all \n with empty strings:
private StringProperty promptText = new SimpleStringProperty(this, "promptText", "") {
#Override protected void invalidated() {
// Strip out newlines
String txt = get();
if (txt != null && txt.contains("\n")) {
txt = txt.replace("\n", "");
set(txt);
}
}
};
A way around (not sure if it is working on all platforms - does on my win) is to use the \r instead:
paragraph.setPromptText(
"Stuff done today:\r"
+ "\r"
+ "- Went to the grocery store\r"
+ "- Ate some cookies\r"
+ "- Watched a tv show"
);
Related
I am working in Java. I have list of parameters stored in a string which is coming form excel. I want to split it only at starting hyphen of every new line. This string is stored in every excel cell and I am trying to extract it using Apache poi. The format is as below:
String text =
"- I am string one\n" +
"-I am string two\n" +
"- I am string-three\n" +
"with new line\n" +
"-I am string-four\n" +
"- I am string five";
What I want
array or arraylist which looks like this
[I am string one,
I am string two,
I am string-three with new line,
I am string-four,
I am string five]
What I Tried
I tried to use split function like this:
String[] newline_split = text.split("-");
but the output I get is not what I want
My O/P
[, I am string one,
I am string two,
I am string, // wrong
three // wrong
with new line, // wrong
I am string, // wrong!
four, // wrong!
I am string five]
I might have to tweak split function a bit but not able to understand how, because there are so many hyphens and new lines in the string.
P.S.
If i try splitting only at new line then the line - I am string-three \n with new line breaks into two parts which again is not correct.
EDIT:
Please know that this data inside string is incorrectly formatted just like what is shown above. It is coming from an excel file which I have received. I am trying to use apache poi to extract all the content out of each excel cell in a form of a string.
I intentionally tried to keep the format like what client gave me. For those who are confused about description inside A, I have changed it because I cannot post the contents on here as it is against privacy of my workplace.
You can
remove line separators (replace it with space) if they don't have - after it (in next line): .replaceAll("\\R(?!-)", " ") should do the trick
\R (written as "\\R" in string literal) since Java 8 can be used to represent line separators
(?!...) is negative-look-ahead mechanism - ensures that there is no - after place in which it was used (will not include it in match so we will not remove potential - which ware matched by it)
then remove - placed at start of each line (lets also include followed whitespaces to trim start of the string). In other words replace - placed
after line separators: can be represented by "\\R"
after start of string: can be represented by ^
This should do the trick: .replaceAll("(?<=\\R|^)-\\s*","")
split on remaining line separtors: .split("\\R")
Demo:
String text =
"- I am string one\n" +
"-I am string two\n" +
"- I am string-three\n" +
"with new line\n" +
"-I am string-four\n" +
"- I am string five";
String[] split = text.replaceAll("\\R(?!-)", " ")
.replaceAll("(?<=\\R|^)-\\s*","")
.split("\\R");
for (String s: split){
System.out.println("'"+s+"'");
}
Output (surrounded with ' to show start and end of results):
'I am string one'
'I am string two'
'I am string-three with new line'
'I am string-four'
'I am string five'
This is how I would do:
import java.util.*;
public class MyClass {
public static void main(String args[]) {
String A = "- I am string one \n" +
" -I am string two\n" +
" - I am string-three \n" +
" with new line\n" +
" -I am string-four\n" +
"- I am string five";
String[] s2 = A.split("\r?\n");
List<String> lines = new ArrayList<String>();
String line = "";
for (int i = 0; i < s2.length; i++) {
String ss = s2[i].trim();
if (i == 0) { // first line MUST start with "-"
line = ss.substring(1).trim();
} else if (ss.startsWith("-")) {
lines.add(line);
ss = ss.substring(1).trim();
line = ss;
} else {
line = line + " " + ss;
}
}
lines.add(line);
System.out.println(lines.toString());
}
}
I hope it helps.
A little explanation:
I will process line by line, trimming each one.
If it starts with '-' it means the end of the previous line, so I include it in the list. If not, I concatenate with the previous line.
looks as if you are splitting the FIRST - of each line, so you need to remove every instance of a "newline -"
str.replace("\n-", '\n')
then Remove the initial "-"
str = str.substring(1);
I'm currently developing an email application and when you go into the view screen it shows you the message at the top and if it is a series of emails, then underneath it will have:
------ Original Message ------
& the previous message below it.
Currently, all of this text is in white but I want to show all text in white apart from:
------ Original Message ------
As this is an email application and different providers format the original message string differently (see examples below:)
----Original Message----
---- Original Message ----
------Original Message------
------ Original Message ------
How would I go about having the whole line that contains 'Original Message' (and the dashes (however many dashes there are)) to be blue?
If this was a normal textView, and I knew the text that would be in the String, then I could use:
String startText = "Test - received<br><br>";
String textColor = "<font color='#0475F7'>-------- Original Message --------</font><br><br>";
String endText = "From: Test 124<br>" + "To: Test 125<br>" + "Subject: " + "<" + "confirm" + ">" + "<br>" + "Sent: January 30, 2017 3:40:42 PM GMT+00:00<br><br>" + "Test";
String text = startText + textColor + endText;
messageTextView.setText(Html.fromHtml(text), TextView.BufferType.SPANNABLE);
But as this is an email application, I would not be able to determine the text that will appear in the String every time, as each email is going to be different. The whole message (so top of the message, 'Original Message' line & the message beneath are all contained within one String).
I made an attempt with the below:
if (message.contains("Original Message")) {
int counter = message.split("-", -1).length - 1;
int sideone = counter / 2;
int sidetwo = counter / 2;
Log.d(TAG, "COUNTER: " + counter);
int startPosition = message.indexOf("-");
int endPosition = message.lastIndexOf("-");
Log.d(TAG, "START POS: " + startPosition + " " + "END POS: " + endPosition);
String requiredString = message.substring(startPosition, endPosition);
Log.d(TAG, "REQUIRED STRING: " + requiredString);
messageTextView.setText(message);
} else {
messageTextView.setText(message);
}
Whilst the counter would tell me how many dashes there are, I could not figure out how to use that to get the whole line with the dashes and the 'Original Message' part in the middle. Also using the requiredString method would work (but cut one dash off of the end) and if the user had used a dash somewhere in their email, then it wouldn't work as it would instead try to get the dashes before the 'Original Message' line.
Therefore, I'm looking for a way to do the following:
Retrieve the whole line in the String that contains the words 'Original Message' and all of the dashes that come with it
Set the colour to blue (#0475F7)
Set the textView with the text of the message at the top (in white) + the 'Original Message' line (in blue) followed by the message at the bottom (in white)
The best way to approach this is with HTML/XML tags. Android has classes that are able to parse HTML/XML and add the necessary styling needed. See this link.
If you don't want to go the HTML route, you can also check out the Span classes.
Hope this helps.
Managed to resolve this by using Spannable (as suggested above) and then checking the configuration.
if (message != null) {
if (message.contains("-------- Original Message --------")) {
Log.d(TAG, "Encromail configuration");
String wordToFind = "-------- Original Message --------";
Pattern word = Pattern.compile(wordToFind);
Matcher match = word.matcher(message);
Spannable wordToSpan = new SpannableString(message);
while (match.find()) {
Log.d(TAG, "Found Original Message string at index " + match.start() + " - " + (match.end() - 1));
wordToSpan.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.electric_blue)), match.start(), match.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
messageTextView.setText(wordToSpan);
} else if (message.contains("------ Original Message ------")) {
Log.d(TAG, "App to app configuration");
String wordToFind = "------ Original Message ------";
Pattern word = Pattern.compile(wordToFind);
Matcher match = word.matcher(message);
Spannable wordToSpan = new SpannableString(message);
while (match.find()) {
Log.d(TAG, "Found Original Message string at index " + match.start() + " - " + (match.end() - 1));
wordToSpan.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.electric_blue)), match.start(), match.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
messageTextView.setText(wordToSpan);
} else if (message.contains("------Original Message------")) {
Log.d(TAG, "BlackBerry 7 configuration");
String wordToFind = "------Original Message------";
Pattern word = Pattern.compile(wordToFind);
Matcher match = word.matcher(message);
Spannable wordToSpan = new SpannableString(message);
while (match.find()) {
Log.d(TAG, "Found Original Message string at index " + match.start() + " - " + (match.end() - 1));
wordToSpan.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.electric_blue)), match.start(), match.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
messageTextView.setText(wordToSpan);
} else {
Log.d(TAG, "Message doesn't contain Original Message string");
messageTextView.setText(message);
}
}
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;
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 use the following code:
if (delanaloge.equals(stari)) {
if (novi.equals("-")) {
zdruzen = " -";
} else {
zdruzen = zdruzen + " " + " - " + novi + "\r";
}
nap = true;
}
\r is appended to create a line break, but it does not generate a line break like I expect. I would like to generate an output similar to this:
- 213
- 232
- 1321
How can I add a line break in my string?
you could use this:
public static String newline = System.getProperty("line.separator");
New line character combinations vary between OS. Windows is \r\n, Unix-like systems such as Linux, FreeBSD, Android and so on is \n and MacOS is \r.
Try whichever suits your development environment.
Try this:
if (delanaloge.equals(stari)) {
if (novi.equals("-")) {
zdruzen = " -";
} else {
zdruzen = zdruzen + " - " + novi + System.getProperty("line.separator");
}
nap = true;
}
try to use \r\n, in some cases \n will work (or every case) .. just try both :)
In JTextPane and other text components \n suffices and seems a good choice. On Windows the document internally stores \r\n so document positions and getText() indices are not equal. System.getProperty("line.separator") is more correct, but \n is so universal.
Use \ n for line breaking in printing the String.
if (delanaloge.equals(stari)) {
if (novi.equals("-")) {
zdruzen = " -";
} else {
zdruzen = zdruzen + " " + " - " + novi + "\n";
}
nap = true;
}
A bit from the typing machines age -
\r is the carriage return and should go back to the line origin.
\n is the new line feed on and does create the new line.
For Windows systems \r\n is a typical new line - and works as on the typing machine - carriage return, then new line.
For Linux based systems it was shorten to just \n. But '\n' is normally recognized by most programs.