JavaFX - Proč není text zarovnán na střed?
Dobrý den,
Mám problém se zarovnáním. Když napíšu např.
import javafx.geometry.VPos;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.scene.text.TextBoundsType;
import javafx.stage.Stage;
public class TextAlignment extends javafx.application.Application {
@Override
public void start(Stage stage) {
var gridPane = new GridPane();
gridPane.setStyle("-fx-background-color: yellow ;");
gridPane.setHgap(10);
gridPane.setVgap(10);
var texx = "EXAMPLE";
for (var i = 0; i < texx.length(); i += 1) {
var text = new Text(String.valueOf(texx.charAt(i)));
text.setBoundsType(TextBoundsType.VISUAL);
text.setTextOrigin(VPos.BOTTOM);
text.setTextAlignment(javafx.scene.text.TextAlignment.CENTER);
text.setFill(Color.BLUE);
var textPane = new TextPane(text);
textPane.setLayoutX(0);
textPane.setMinHeight(100);
textPane.setMaxHeight(100);
gridPane.add(textPane, i, i);
}
stage.setScene(new Scene(new Pane(gridPane), 600, 800));
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Objekt textPane je vytvořen pomocí třídy níže
import javafx.geometry.Orientation;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
public class TextPane extends javafx.scene.layout.Region {
private final Text text;
public TextPane(Text text) {
this.text = text;
getChildren().add(text);
}
@Override
protected void layoutChildren() {
adjustFontSize(getHeight());
text.setY(getHeight());
text.setX(0);
}
private void adjustFontSize(double height) {
var textHeight = text.getBoundsInLocal().getHeight();
if (Math.abs(height - textHeight) > 1) {
var currentFont = text.getFont();
var fontSize = currentFont.getSize();
text.setFont(Font.font(currentFont.getFamily(), height * fontSize / textHeight));
System.out.println(text.getLayoutBounds().getWidth());
}
}
@Override
protected double computePrefWidth(double height) {
adjustFontSize(height);
return text.getBoundsInLocal().getWidth();
}
@Override
public Orientation getContentBias() {
return Orientation.VERTICAL;
}
}
Tak se zobrazí
Proč je, prosím Vás, text špatně zarovnaný a jak to opravím?
Děkuji