【发布时间】:2012-05-24 14:21:39
【问题描述】:
我需要在 JavaFX 2.1 中通过窗格动态创建矩形。接下来我需要在矩形上居中/换行/截断文本。文本必须适合矩形。我可以使用以下代码将文本居中并换行,但是,如果文本长度太长,它将出现在矩形之外。我想在 StackPane 中创建类似于 Label 的行为,本质上,如果 Rectangle 增长,Text 会随之增长,但始终保持在 Rectangle 的中心,如果 Text 不能放入 Rectangle 中,它将被相应地截断。
Rectangle r;
Text t;
...
//center and wrap text within rectangle
t.wrappingWidthProperty().bind(rect.widthProperty().multiply(0.9);
t.xProperty().bind(rect.xProperty().add(rect.widthProperty().subtract(t.boundsInLocalProperty().getValue().getWidth().divide(2)));
t.yProperty().bind(rect.yProperty().add(rect.heightProperty().divide(2)));
t.setTextAlignment(TextAlignment.CENTER);
t.setTextOrigin(VPos.CENTER);
我可以使用哪些属性来实现这一点,或者有更好的方法吗?
【问题讨论】:
-
为什么不直接使用带有背景颜色的标签?