Get a StackPane's width


Question

I can't figure out how to get a StackPane's width :

If i refer to http://docs.oracle.com/javafx/2.0/api/javafx/scene/layout/StackPane.html, a StackPane's dimensions should adapt to it's content :

A stackpane's parent will resize the stackpane within the stackpane's resizable range during layout. By default the stackpane computes this range based on its content as outlined in the table below.

preferredWidth left/right insets plus the largest of the children's pref widths.

Syntax here is scala, but the issue concerns javafx :

import javafx.scene.layout.StackPane
import javafx.scene.shape.Rectangle

class Bubble() extends StackPane {
val rect = new Rectangle(100, 100)

getChildren.add(rect)

println(rect.getWidth)
println(this.getWidth)
}

Output :
>> 100.0
>> 0.0 <- Why isn't it 100 ?

Is this a bug or the awaited behaviour ? How can i get a StackPane's content width ?

Thanx

1
3
4/11/2012 2:09:34 PM

Accepted Answer

Layout managers (and actually all resizable objects) don't update their bounds until application being actually shown. Rectangle gives width 100 because it's default value with your constructor.

See next code:

@Override
public void start(Stage stage) throws Exception {
    StackPane root = new StackPane();
    Rectangle rect = new Rectangle(100, 100);
    root.getChildren().add(rect);

    // 100 - 0
    System.out.println(rect.getWidth());
    System.out.println(root.getWidth());

    stage.setScene(new Scene(root));

    // 100 - 0
    System.out.println(rect.getWidth());
    System.out.println(root.getWidth());

    stage.show();

    // 100 - 100
    System.out.println(rect.getWidth());
    System.out.println(root.getWidth());
}

So you need either wait StackPane to be shown. Or better rely on JavaFX on that matter and use binding. E.g.

    stage.titleProperty().bind(root.widthProperty().asString());
3
4/11/2012 2:58:27 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon