使用Java FX,文本x和y坐标指的是文本的左下角。如何使坐标参考左上角?例如,如果在原点(0,0)处绘制了文本,则该文本将退出屏幕,但在这种情况下,我们希望将其显示在左上方。
public class JavaFxOriginText extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Group root = new Group();
Scene scene = new Scene(root, 100, 50, Color.WHITE);
primaryStage.setScene(scene);
primaryStage.show();
for(int i=0; i<5; i++) {
Text text = new Text(0, i*10, "Hello World! " + i);
text.setFill(Color.BLACK);
root.getChildren().add(text);
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是显示中缺少“ Hello World!0”。
Set the text origin to VPos.TOP (default is VPos.BASELINE):
Text text = new text(15, 0, "The Thirty-Nine Steps");
text.setTextOrigin(VPos.TOP);
Run Code Online (Sandbox Code Playgroud)
Defines the origin of text coordinate system in local coordinates.
You might also wish to set the text bounds type to TextBoundsType.VISUAL (default is TextBoundsType.LOGICAL):
text.setBoundsType(TextBoundsType.VISUAL);
Run Code Online (Sandbox Code Playgroud)
The geometry of text can be measured either in terms of the bounds of the particular text to be rendered - visual bounds, or as properties of the font and the characters to be rendered - logical bounds. Visual bounds are more useful for positioning text as graphics, and for obtaining tight enclosing bounds around the text.