I want to add UTF-8 Farsi characters in JavaFX but when I add a label with Persian content it shows some weird results.
Do I have to use a specific plugin or configuration to handle this issue?
Persian is right to left?
In which case you want to use a version of JavaFX with RTL support. That would be JavaFX 8 (included in JDK8). There is a preview available here.
Make sure you have loaded and are using a font which includes the glyphs for Persian characters.
Here is some sample JavaFX code (copied from Oracle JavaFX tutorials) for displaying something which looks to me like Persian script.
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;
public class JavaFXBidiText extends Application {
@Override
public void start(Stage stage) throws Exception {
TextFlow textFlow = new TextFlow();
Font font = new Font("Tahoma", 48);
Text text1 = new Text("He said \u0627\u0644\u0633\u0644\u0627\u0645");
text1.setFill(Color.RED);
text1.setFont(font);
Text text2 = new Text(" \u0639\u0644\u064a\u0643\u0645 to me.");
text2.setFill(Color.BLUE);
text2.setFont(font);
textFlow.getChildren().addAll(text1, text2);
Group group = new Group(textFlow);
Scene scene = new Scene(group, 650, 150, Color.WHITE);
stage.setTitle("Hello Bidi Text");
stage.setScene(scene);
stage.show();
}
}
Other comments on this question and answers regarding using and interpreting the correct character encoding are also valid, so this answer is not completely authoritative.
If the source file is ascii encoded, then you can use the \u
values to represent unicode values of non-ascii characters, as shown in the example above.
I think (though I haven't tried), if the source file (the .java
file for the class or the property file for the resource) is UTF-8 encoded (it must be saved as UTF-8 encoding, not another character set, for example setting the file encoding in the Intellij IDEA editor) then you can directly put the unicode type characters in Strings like you would do with normal ASCII characters without using the /u
encoding. If you do so, the compiler or build tool must be configured to work with UTF-8 encoded files. See for example, with Maven: How to configure encoding in Maven?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With