java javafx 如何设置文本或标签的中心位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30511324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javafx how to set center position for text or label?
提问by mrdaliri
How to set centerX and centerY for Text
or Label
node in JavaFX?
如何在JavaFX中为Text
或Label
节点设置centerX和centerY ?
AFAIK, there is no specific property (or method) for center position, but there are setLayoutX, setLayoutY
methods + relocate
, which I can't understand how they work.
AFAIK,中心位置没有特定的属性(或方法),但是有setLayoutX, setLayoutY
方法 + relocate
,我无法理解它们是如何工作的。
回答by agonist_
You have to tell to your parent layout how to display children. Not children how to display themself.
您必须告诉您的父布局如何显示子项。不是孩子如何展示自己。
For example if your button is inside an Hbox just do :
例如,如果您的按钮在 Hbox 内,请执行以下操作:
hbox.setAlignment(Pos.CENTER)
You should read Working with layoutfor a better understanding
您应该阅读使用布局以更好地理解
回答by NM Naufaldo
If you want to center text in Pane
container based on mouse coordinate, try this one
如果你想Pane
根据鼠标坐标在容器中居中文本,试试这个
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class CenterTextWithCoordinateDemo extends Application {
@Override
public void start(Stage primaryStage){
Pane pane = new Pane();
pane.setOnMousePressed(event -> {
Circle circle = new Circle();
circle.setRadius(10);
circle.setFill(Color.BLUE);
circle.setCenterX(event.getX());
circle.setCenterY(event.getY());
pane.getChildren().add(circle);
Text text = new Text();
text.setText("This is a long text");
text.setX(event.getX());
text.setY(event.getY());
text.setX(text.getX() - text.getLayoutBounds().getWidth() / 2);
text.setY(text.getY() + text.getLayoutBounds().getHeight() / 4);
pane.getChildren().add(text);
});
Scene scene = new Scene(pane,600, 600);
primaryStage.setTitle("Center Text With Coordinate Demo");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}