1

Here is the code:

package je3.thread;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;

/**
 * Text seemed to be anchored at the bottom left corner.
 * See screenshot here: http://i60.tinypic.com/2mnnmrn.jpg
 */
public class ShowText extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        Pane pane = new Pane();
        pane.setPadding(new Insets(0, 0, 0, 0));
        Text text1 = new Text(20, 20, "Programming fun");
//        text1.setFont(Font.font("Courier", BOLD, FontPosture.ITALIC, 15));
        Text text2 = new Text(30, 30, "Programming fun");
        Text text3 = new Text(40, 40, "Programming fun");
//        text3.setFill(Color.RED);
//        text3.setUnderline(true);
        pane.getChildren().addAll(text1, text2,text3);
        Scene scene = new Scene(pane);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

Result:

enter image description here

What I am looking for is a method to specify a coordinate and anchor the center of a given text object to that coordinate.

qed
  • 22,298
  • 21
  • 125
  • 196
  • possible duplicate of [Is there an easier (lighter) way to center text in a "zone" with JavaFX 8?](http://stackoverflow.com/questions/28075994/is-there-an-easier-lighter-way-to-center-text-in-a-zone-with-javafx-8) – eckig Feb 03 '15 at 13:21
  • Not a duplicate. Putting text in the __center of a zone__ is totally different from putting text at a certain coordinate and anchoring the __center of the text__ to that coordinate. – qed Feb 03 '15 at 13:25
  • Well, two things: Your question lacks some descriptive text clarifying what you intend to ask. And secondly: The linked possible duplicate gives you a clear hint on how to center text in JavaFX in general. With that knowledge it is rather easy to write the solution to your problem.. – eckig Feb 03 '15 at 13:29
  • ok, I have added some descriptive text of my goal. I can't see an easy solution from looking the link you posted. If it's obvious to you, why not write up answer? ;-) – qed Feb 03 '15 at 13:35

2 Answers2

2

Something like this then:

private Text centerTextOnCoordinate( String text, double x, double y )
{
    Text  txtShape = new Text( x, y, text );
    txtShape.setX( txtShape.getX() -  txtShape.getLayoutBounds().getWidth() / 2 );
    return  txtShape;
}
Jurgen
  • 2,138
  • 12
  • 18
1

You could try to create an Label instead of Text, and bind the translateX to the half negative value of the width, like this:

label.translateXProperty().bind(label.widthProperty().divide(2).negate());
// same way to y axis, if needed
label.translateYProperty().bind(label.heightProperty().divide(2).negate());