简体   繁体   中英

When is updated a Label's widthProperty?

I use a Pane to print some Label by adding them to its children list. For some reason, I need to bind a label width, but when I do something like :

public class LabelTestApp extends Application
{
    private Pane root = new Pane();
    private Label myLabel = new Label("test");

    public static void main(String[] args)
    {
        launch(args);
    }

    @Override
    public void start(Stage stage)
    {
        root.getChildren.add(myLabel);
        System.out.println(myLabel.widthProperty());
        stage.setScene(new Scene(root, 500, 500);
        stage.show();
     }
}

It seems like the Label doesn't update its width. When I print it with :

System.out.println(myLabel.widthProperty());

I get :

ReadOnlyDoubleProperty [bean : Label@xxxxxxxx[styleClass = label]'test', name:width, value: 0.0]

So I suppose that the width of a Label is calculated during Layout, and since a Pane doesn't have any Layout manager, it is never calculated, am I right ?

If so, how am I supposed to get this width ?

If not, the problem is somewhere else, and I can't figure out where.

For informations : I need to use a Pane to draw some Shape , and control their placement. The purpose of the Label is to print some informations on the shapes. I need the width of the Label because they are some Line on the shapes, and I don't want them to cross the Label.

Don't hesitate to ask for further informations.

JavaFX only lays out components which are visible.

You can see this if you try something like this:

final Label myLabel = new Label("test");
final Pane myPane = new Pane(myLabel);

System.out.println(myLabel.getWidth());

stage.setScene(new Scene(myPane, 640, 480));
stage.show();

System.out.println(myLabel.getWidth());

which prints

0.0
19.5

As you can see here, the label's size is not set until stage.show() is called. You can also override Pane to see layoutChildren() is called for the first time at this point.

As a sidenote, if you want to find out the width of some text without showing it in a Stage, you can make a Text node (instead of a label) and get its preferred width, eg

new Text("test").prefWidth(0)

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM