Reputation: 484
How can I get the center of the text to be dynamically positioned at the center of the circle? Currently the text is created with the given X and Y coordinates being at the bottom left, however I want them to be the center of the text. (The red dot is the center of the circle which is where I want the center of the text).
public class CenteredText extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage mainStage) throws Exception {
Pane pane = new Pane();
Circle circle = new Circle(250, 250, 100);
Circle innerCircle = new Circle(250, 250,
98);
innerCircle.setFill(Color.WHITE);
Text text = new Text(250, 250, "test" );
// coords given to text
Circle coords = new Circle(250, 250, 1);
pane.getChildren().addAll(circle, innerCircle, text, coords);
BorderPane root = new BorderPane();
root.setCenter(pane);
mainStage.setScene(new Scene(root, 500, 500));
mainStage.show();
}
}
Upvotes: 1
Views: 671
Reputation: 44413
To center the text vertically, set its text origin to CENTER.
You will need to compute the X-coordinate yourself. Since you want half of the text’s overall width to be left of 250, you need to know that overall width in order to do the math.
CSS is not applied to nodes until they are in a scene. But you can forego the CSS and set the font directly, so the program can immediately know the Text object’s proper preferred width:
Text text = new Text(250, 250, "test");
text.setFont(Font.font("Arial", 24));
double width = text.prefWidth(-1);
text.setX(250 - width / 2);
text.setTextOrigin(VPos.CENTER);
Upvotes: 2
Reputation: 4390
The Label control will do this for you:
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) {
stage.setTitle("Centered Text");
Circle circle = new Circle(100);
Circle innerCircle = new Circle(98);
innerCircle.setFill(Color.WHITE);
StackPane circles = new StackPane(circle, innerCircle);
Label label = new Label("test", circles);
label.setContentDisplay(ContentDisplay.CENTER);
Pane p = new Pane(label);
Scene scene = new Scene(p);
stage.setScene(scene);
stage.show();
}
}
Upvotes: 0