我尝试在屏幕上预渲染一些Text
元素以检索它们的宽度,然后再在屏幕上呈现它们:
Group offScreenRoot = new Group();
Scene offScreen = new Scene(offScreenRoot, 1024, 768);
Set<Text> textSet = new HashSet<>();
Text textText = new Text(getText());
textSet.add(textText);
Text idText = new Text(getId());
textSet.add(idText);
for (String s : getStrings()) {
textSet.add(new Text(s));
}
for (Text text : textSet) {
text.setStyle("-fx-font-size: 48;"); // <- HERE!
text.applyCss();
offScreenRoot.getChildren().add(text);
}
for (Text text : textSet) {
System.out.println(text.getLayoutBounds().getWidth());
}
我通过CSS应用较大的字体大小,但这并没有被提取。相反,Text
和它一样宽,以默认字体大小呈现(我猜)。
有没有办法在屏幕外呈现Text
并根据CSS字体大小获取实际宽度值?
答案 0 :(得分:0)
我不确定您的代码的用途。使用MCVE本来会更容易,下次请记住。
我认为你犯了一些简单的错误。查看applyCss definition您应该在父节点上应用applyCss,而不是在节点上。
文档中另一个重要的事情是:
如果节点的场景不为空
不幸的是,当您应用CSS时,文本的场景为空,因为它尚未添加到其父级。
text.applyCss();
offScreenRoot.getChildren().add(text);
所以有两个解决方案,如下面的注释中的代码所述(特别是在你将文本添加到父级的for循环中):
public class MainOffscreen extends Application {
private List<String> stringsList = new ArrayList<>();
@Override
public void start(Stage primaryStage) throws Exception {
// Populates stringsList
stringsList.add("String1");
stringsList.add("String2");
stringsList.add("String3");
stringsList.add("String4");
VBox offscreenRootVbox = new VBox(10.0);
Scene offScreen = new Scene(offscreenRootVbox, 900, 700);
// Replace the Hashset by list in order to keep order, more interesting for testing.
List<Text> textSet = new ArrayList();
// Text text.
Text textText = new Text("Text");
textSet.add(textText);
// Text id.
Text idText = new Text("Id");
textSet.add(idText);
// Populate String list.
for(String s: stringsList) {
textSet.add(new Text(s));
}
// Print the width of Texts before applying Css.
for(Text text: textSet) {
System.out.println("BEFORE Width of " + text.getText() + " : " + text.getLayoutBounds().getWidth());
}
System.out.println("\n----------\n");
for(Text text: textSet) {
text.setStyle("-fx-font-size: 48;"); // <- HERE!
// First add it to the parent.
offscreenRootVbox.getChildren().add(text);
// Either apply the CSS on the each Text, or Apply it on the parent's Text, I choose the
// second solution.
// text.applyCss();
}
// Apply the css on the parent's node
offscreenRootVbox.applyCss();
for(Text text: textSet) {
System.out.println("AFTER Width of " + text.getText() + " : " + text.getLayoutBounds().getWidth());
}
// primaryStage.setScene(offScreen);
// primaryStage.show();
}
}
它给出了这个输出:
BEFORE Width of Text : 22.13671875
BEFORE Width of Id : 10.259765625
BEFORE Width of String1 : 37.845703125
BEFORE Width of String2 : 37.845703125
BEFORE Width of String3 : 37.845703125
BEFORE Width of String4 : 37.845703125
----------
AFTER Width of Text : 88.546875
AFTER Width of Id : 41.0390625
AFTER Width of String1 : 151.3828125
AFTER Width of String2 : 151.3828125
AFTER Width of String3 : 151.3828125
AFTER Width of String4 : 151.3828125
希望这会对你有所帮助。