![Mastering JavaFX 10](https://wfqqreader-1252317822.image.myqcloud.com/cover/811/36699811/b_36699811.jpg)
上QQ阅读APP看书,第一时间看更新
Adding Text to the JavaFX scene
The last-but-not-least shape to cover is Text. Text draws letters in various fonts. Text weight, posture, and size are controlled by the Font API:
// chapter2/other/TextDemo.java
Text txt = new Text("Hello, JavaFX!");
txt.setFont(Font.font ("Courier New", FontWeight.BOLD, FontPosture.ITALIC, 20));
Text color is controlled through the standard setFill() method, which means we can use all functionality of Paint for text as well:
// gradient fill, see details few sections below
Stop[] stops = new Stop[]{new Stop(0, Color.BLACK), new Stop(1, Color.DARKGRAY), new Stop(0.5, Color.ANTIQUEWHITE)};
LinearGradient gradient = new LinearGradient(50, 50, 250, 50, false, CycleMethod.NO_CYCLE, stops);
txt.setFill(gradient);
The output will be as follows:
![](https://epubservercos.yuewen.com/0A344C/19470392808882006/epubprivate/OEBPS/Images/Chapter_113.jpg?sign=1738994937-H3mkkYZHTGccfCmN5IOL5BSX3ehHhqSA-0-6b02745ac9e2052b78253cf5552f39cf)
Text supports multiline strings with a \n delimiter.
For combining different text styles there is the TextFlow class, which takes multiple Text objects as children:
Text txt1 = new Text("Text1");
txt1.setFont(Font.font ("Courier New", 15));
Text txt2 = new Text("Text2");
txt2.setFont(Font.font ("Times New Roman", 20));
Text txt3 = new Text("Text3");
txt3.setFont(Font.font ("Arial", 30));
TextFlow textFlow = new TextFlow(txt1, txt2, txt3);
The output is as follows:
![](https://epubservercos.yuewen.com/0A344C/19470392808882006/epubprivate/OEBPS/Images/Chapter_64.jpg?sign=1738994937-fTWWHMofYncOUHXy1HKz6rurPKLoEED9-0-316c2f36d3b2b6c19af7ad35e4e75908)
Note that Text and TextFlow support bi-directional text, which will be shown left-to-right when required.
Now we are done with the overview of shapes. Let's look into the common properties all shapes have.