Get Node Size - JavaFX 2

I am trying to switch to JavaFX from Swing. But I can not find how to get the width and height of the node.

So here is some code.

Label label = new Label();
label.setText("Hello");
label.setFont(new Font(32));

System.out.println(label.getPrefWidth());
System.out.println(label.getWidth());
System.out.println(label.getMinWidth());
System.out.println(label.getMaxWidth());

Results:

-1.0
 0.0
-1.0
-1.0

Same thing in Swing:

JComponent.getPreferredSize().width
JComponent.getPreferredSize().height

thank


After editing:

Why does this not work for me?

public class Dimensions extends Application {

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

    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello World!");

        primaryStage.setScene(new Scene(new MyPanel(), 500, 500));
        primaryStage.centerOnScreen();
        primaryStage.setResizable(false);
        primaryStage.show();
    }
}
public class MyPanel extends Pane {

    public MyPanel() {  
        Label label = new Label();
        label.setText("Hello");
        label.setFont(new Font(32));

        getChildren().add(label);

        label.relocate(150, 150);

        System.out.println(label.getWidth());
    }
}
+5
source share
2 answers

Width and height are not initialized until you put the node in the container actually placed on the stage, because they can vary depending on the type of container.

Try the following:

public void start(Stage primaryStage) {
    Label label = new Label();
    label.setText("Hello");
    label.setFont(Font.font("Arial", 32));

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

    StackPane root = new StackPane();
    root.getChildren().add(label);

    Scene scene = new Scene(root, 300, 250);

    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();

    System.out.println("------");
    System.out.println(label.getWidth());
}

Make the following changes to your code:

public class Dimensions extends Application {

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

    public void start(Stage primaryStage) {
        MyPanel myPanel = new MyPanel();
        primaryStage.setScene(new Scene(myPanel, 500, 500));
        primaryStage.show();

        System.out.println(myPanel.label.getWidth());
    }
}

class MyPanel extends Pane {
    public Label label;

    public MyPanel() {

        label = new Label();
        label.setText("Hello");
        label.setFont(new Font(32));
        getChildren().add(label);
        label.relocate(150, 150);
    }
}
+7
source

After adding the node to the screen, you can use:

thisNode.getBoundsInParent().getHeight(); //Returns height of object in parent container.
+8
source

All Articles