How to get label.getWidth() in javafx

前端 未结 4 906
余生分开走
余生分开走 2021-01-03 04:11

always when i try to get the width of an Array in Java it just returns 0 and i dont know why. Can somebody explain to me how it is done right?

                       


        
相关标签:
4条回答
  • 2021-01-03 04:21

    To get the width you need to call prefWidth(-1) and prefHeight(-1) the layout bounds are only set once the control is layouted through resizeRelocate

    To get the correct width before the stage is shown you also need to call impl_processCSS(true) which is an NONE public API but there's nothing better at the moment IIRC

     HBox h = new HBox();
     Label l = new Label("Hello");
     h.getChildren().add(l);
     Scene s = new Scene(h);
     l.impl_processCSS(true);
     System.err.println(l.prefWidth(-1)+"/"+l.prefHeight(-1));
    
    0 讨论(0)
  • 2021-01-03 04:29

    I don't think the width will be calculated until the Label is shown: add it to a Parent that is visible and you should get a non-zero result.

    0 讨论(0)
  • 2021-01-03 04:30

    Another approach is to calculate the string width of the label's textProperty using Fontloader.computeStringWidth(text, font) which would output the pixel width of the label's textProperty, and is considerably similar to getting the label's width when the label is layouted at the later part.

    For an instance:

        FontLoader fontLoader = Toolkit.getToolkit().getFontLoader();
        Label label = new Label("My name is Warren. I love Java.");
        label.setFont(Font.font("Consolas", FontWeight.THIN, FontPosture.REGULAR, 16));
        System.out.println("The label's width is: " + fontLoader.computeStringWidth(label.getText(), label.getFont()));
    

    The output is:

    The label's width is: 272.70312
    

    To test:

        FontLoader fontLoader = Toolkit.getToolkit().getFontLoader();
        Label label = new Label("My name is Warren. I love Java.");
        label.setFont(Font.font("Consolas", FontWeight.THIN, FontPosture.REGULAR, 16));
        System.out.println("The label's textProperty string width is: " + fontLoader.computeStringWidth(label.getText(), label.getFont()));
        System.out.println("Label's width before layouted: " + label.getWidth());
        primaryStage.setScene(new Scene(new StackPane(label), 300, 250));
        primaryStage.show();
        System.out.println("Label's width after layouted: " + label.getWidth());
    

    Here's the output

    The label's textProperty string width is: 272.70312
    Label's width before layouted: 0.0
    Label's width after layouted: 273.0
    

    Comparably, they are the same. Hope this helps.

    0 讨论(0)
  • 2021-01-03 04:36

    You can try the following:

    func foo()
    {
        label.layout();
    
        Platform.runLater(()->
        {
            System.out.println(label.getWidth());
        });
    }
    
    0 讨论(0)
提交回复
热议问题