Tuesday, July 21, 2009

JavaFX - Operations on Strings

Use any quote you like

Ok, so let's start with Strings. You can use both single and double quote to define simple String. Both works:
var a = 'Single';
var b = "Double";
Also you can use another quote in String as part of this String. I.e. if you use single quote to declare String, you can put double quote inside, and if you use double one, you can put single one inside.
var a = 'This is String "with double quote" inside';
var b = "This is String 'with single quote' inside";
Both are valid Strings. However, if you need to use both types in your String, you have to escape it:
var a = 'Here we have "double quotes" and \'single quotes\' in one String';
var b = "And 'here' \"too!\""
Expressions in String

In JavaFX you can also embed expressions in Strings. To do it, put expression in curly brackets:
println("2 + 3 = {2+3}");
This code prints: 2 + 3 = 5 By the way, you can see new println function here. It is in javafx.lang.Builtins, which is included automatically in all JavaFX scripts.

As expression, you can use also variables, function calls, operations on variables (like in example above) etc.

Concatenation

You don't need any operator to concatenate Strings. If you split String over few lines, you don't have to add "+" at the end of each line.
var one = "This" 'is'
"one"
'String';
println(one);
And it outputs: ThisisoneString

Formatting

You can quite easy format Strings in JavaFX. It is based on java.util.Formatter class.

println("{%x 12}");
println("{%c 120}");
var d = Date{};    //Here new java.util.Date is created
println("{%tH d}:{%tM d}:{%tS d}")
And it prints:
c x 23:12:18 First there is 12 in hex, then there is character, which code in Unicode is 120, and then it is Date object, first we get hour from it, then minute, and then second.

Localization

Localization in JFX is realized by properties files. It's name is connected with your script (file with your JFX code) by name convention. If your script is House.fx, then your localization file is House_en.fxproperties and it has to be somewhere in the classpath. fxproperties file looks like this:
"dog"="pies"
"cat"="kot"
And then, to use it in script:
println(##"dog");
println(##[cat]"Cat");
If there is fxproperties found, it is used. If not found, default is used. Default is either properties key (like "dog" in above example) or another word (like "Cat", not "cat" which is only fxproperties key).

No comments: