获取窗格大小而不将其添加到场景中(在JavaFX中)?

时间:2016-08-29 15:45:08

标签: javafx size bounds pane

如果我创建一个public static class CarPartsLibary { public static string factoryId = "fgk4548j4t5jig3"; public static string engineId = "fgfgj34lk45l3lj"; public static string bodyId = "45kjgiu590dkjr"; public static bool typeCar = true; public static bool autoStart = true; public static bool allWheelDrive = true; public static bool dieselEngine = false; } var car = CarPartsLibary.typeCar; var factory = GetLocation(CarPartsLibary.factoryId); (其中包含节点),如何在不在屏幕上呈现的情况下计算宽度/高度?

我正在尝试创建一个文档(在内存中)并将其发送到打印机。问题是,我需要计算需要多少页面以及 那样做 才能获得文档的维度。

我试验的一个简单例子:

Pane

我输出的所有内容都是Label testLabel1 = new Label("TEST1"); Label testLabel2 = new Label("TEST no. 2"); GridPane testGl = new GridPane(); testGl.add( testLabel1, 1, 1 ); testGl.add( testLabel2, 2, 2 ); VBox testVBox = new VBox( testGl ); Pane testPane = new Pane( testVBox ); //I read that this might be required testPane.applyCss(); testPane.layout(); //Also that a delay is needed for the fx tread to update testPane // (but shouldn't this all be in the same thread since it is in the same function? // It doesn't seem to help). Platform.runLater( ()->{ System.out.println( ">>> "+ testPane.getBoundsInLocal().getWidth() ); }); 。请注意,在我正在开发的程序中,我在"容器内有多个>>> 0.0" Pane。因此,变量Pane

谢谢。

1 个答案:

答案 0 :(得分:0)

您需要将Pane添加到Scene才能使布局正常工作。然而,无需显示Scene,也无需在此场景中保留Pane

Label testLabel1 = new Label("TEST1");
Label testLabel2 = new Label("TEST no. 2");
GridPane testGl = new GridPane();
testGl.add(testLabel1, 1, 1);
testGl.add(testLabel2, 2, 2);
VBox testVBox = new VBox(testGl);
Pane testPane = new Pane(testVBox);

// add testPane to some scene before layouting
Scene testScene = new Scene(testPane);

testPane.applyCss();
testPane.layout();

System.out.println(">>> " + testPane.getBoundsInLocal().getWidth());

// Pane could be removed from scene
Group replacement = new Group();
testScene.setRoot(replacement);

请注意,如果要从Scene中删除根,则必须将其替换为非空节点。