JavaFX のテキストをセンタリングする

JavaFX で文字列のセンタリング - hidemonのブログ

外しているかもしれませんが...
JavaFX のテキストをセンタリングする為に MigLayout を使って面倒を感じられているようなので。

外部のライブラリを使わずに標準の JavaFX API だけで文字列をセンタリングできます。


一つはテキストのレンダリング後のサイズを使ってセンタリングします。
どうやら以前は問題があったとのことですが、今は動作します。

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.TextOrigin;

var width = 200;
var height = 200;

Stage {
    title: "Text Centering 1"
    width: 250
    height: 250
    scene: Scene {
        var text: Text;
        content: [
                    Rectangle {
                        width: bind width
                        height: bind height
                        fill: Color.YELLOWGREEN
                    }
                    text = Text {
                        font : Font {
                            size : 16
                        }
                        content: "Hello"
                        textOrigin: TextOrigin.TOP
                        translateX: bind (width - text.boundsInLocal.width) / 2;
                        translateY: bind (height - text.boundsInLocal.height) / 2;
                    }
        ]
    }
}

実行結果


二つ目の方法は JavaFX 1.2 から追加されたレイアウトの一つ Stack を使う方法。
Stack はその上に配置されたノードをデフォルトでセンタリングしながら重ねて積み上げていくレイアウトです。
このデフォルトは nodeHPos, nodeVPos の設定値を変えることで変更できます。

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.shape.Rectangle;
import javafx.scene.layout.Stack;
import javafx.scene.paint.Color;

var width = 200;
var height = 200;

Stage {
    title: "Text Centering 2"
    width: 250
    height: 250
    scene:  Scene {
        content: [
            Stack {
                content: [
                    Rectangle {
                        width: bind width
                        height: bind height
                        fill: Color.YELLOWGREEN
                    }
                    Text {
                        font : Font {
                            size : 16
                        }
                        content: "Hello"
                    }
                ]
            }
        ]
    }
}

実行結果


他にも方法はあるかも知れませんが、ぱっと思いつくのはこんな感じ。外していたらごめんなさい。