1

I add some child nodes to a VBox, such as button and text. So, the VBox's width should be larger than 0, as it's showing on the scene.

But when I call the width value, it prints out 0.

Examples:

vbox.getWidth();      // prints 0
vbox.widthProperty(); // prints 0

How do I get the right width of vbox?

Jonny Henly
  • 4,023
  • 4
  • 26
  • 43
devDNA
  • 133
  • 6
  • Please review both, [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask) and [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – Jonny Henly May 04 '16 at 03:55
  • Is the vbox already showing in a scene when you call `getWidth()`? – jns May 04 '16 at 05:21
  • Possible duplicate of [Get the height of a node in JavaFX (generate a layout pass)](http://stackoverflow.com/questions/26152642/get-the-height-of-a-node-in-javafx-generate-a-layout-pass) – fabian May 04 '16 at 16:33

2 Answers2

1

Before the appearance of your scene, the width and height of a VBox or any Node is not initialized. That's why you are getting 0 as a result. Try to get the size after the scene is shown in its stage. That way it will show the correct size.

Harshita Sethi
  • 2,035
  • 3
  • 24
  • 46
0

Try this:

vbox.widthProperty().addListener(e -> System.out.println(vbox.getWidth()));