I am trying to jump to JavaFX from Swing. But I can't find how to get the width and the height of a node.
So, here is a bit of 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());
The results are:
-1.0
0.0
-1.0
-1.0
The same thing in Swing is:
JComponent.getPreferredSize().width
JComponent.getPreferredSize().height
Thank you
After edit:
Why this isn't working 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());
}
}
Once the node is added to the screen you can use:
thisNode.getBoundsInParent().getHeight(); //Returns height of object in parent container.
Width and height are not initialized until you put node in a container actually placed on the scene, because they can change depending on container type.
Try next:
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());
}
In your code make next changes:
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With