Reputation: 7358
How to set centerX and centerY for Text
or Label
node in JavaFX?
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.
Upvotes: 3
Views: 23837
Reputation: 1160
If you want to center text in Pane
container based on mouse coordinate, try this one
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);
}
}
Upvotes: 0
Reputation: 5032
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.setAlignment(Pos.CENTER)
You should read Working with layout for a better understanding
Upvotes: 5