1

在自定义 JavaFX UI 控件中,我想在控件的角落放置一些文本。这是我的 Skin 类的源代码:

double width = control.getWidth();
double height = control.getHeight();

Text test1Text = new Text(0, 0, "top left");
Text test2Text = new Text(0, height-1, "bottom left");
Text test3Text = new Text("top right");
test3Text.relocate(width - test3Text.getLayoutBounds().getWidth(), 0);
Text test4Text = new Text("bottom right");
test4Text.relocate(width - test4Text.getLayoutBounds().getWidth(), height-1);

不幸的是,无论我是在给定坐标处构造文本,还是在没有坐标的情况下构造文本并在之后将其重新定位,这似乎都会有所不同:

  • 在第一种情况下,构造函数中的坐标将是文本的左下角坐标。
  • 在第二种情况下,给定的坐标将是左上角的坐标。

对于这种奇怪的行为有什么想法吗?

4

2 回答 2

3

Text正在从 (0,0) 位置向右和向上绘制。例如,如果您创建new Text("Hello")并要求它边界,您将看到它们的垂直坐标为负[minX:0.0, minY:-12.94921875]

恕我直言,下一个原因是:Text在控件中绘制,他们更关心文本的基线。想象一下带有文本“water”和“Water”的 2 个按钮——你真的希望它们与基线对齐,而不是左上角:

在此处输入图像描述

relocate()另一方的方法使用常规Node的 s 并操作总是为左上角计算的布局。

于 2013-03-01T13:52:51.900 回答
1

由于 JavaFX 的大部分部分都是开源的,因此这里是 (JavaFX 8)
javafx.scene.text.Textjavafx.scene.Node的代码。
我无法深入研究,但很明显Text constructorandNode#relocate()正在做不同的事情:
Text constructor

public Text(double x, double y, String text) {
    this(text);
    setX(x);
    setY(y);
}

节点#relocate()

public void relocate(double x, double y) {
        setLayoutX(x - getLayoutBounds().getMinX());
        setLayoutY(y - getLayoutBounds().getMinY());

        PlatformLogger logger = Logging.getLayoutLogger();
        if (logger.isLoggable(PlatformLogger.FINER)) {
            logger.finer(this.toString()+" moved to ("+x+","+y+")");
        }
}

这都是我的想法,对不起。

于 2013-02-28T20:02:06.867 回答