上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:
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:
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.