title: Measure the length of text in JavaFX
body: <p>Here is a simple program that I wrote to have a button on the stage over a rounded rectangle background.  </p>
  
  <pre><code>package definitive_guide;
  
  import java.awt.FontMetrics;
  import java.awt.Graphics;
  import java.awt.Toolkit;
  
  import javafx.application.Application;
  import javafx.scene.Scene;
  import javafx.scene.SceneBuilder;
  import javafx.scene.control.Button;
  import javafx.scene.control.ButtonBuilder;
  import javafx.scene.layout.Region;
  import javafx.scene.layout.StackPane;
  import javafx.scene.layout.StackPaneBuilder;
  import javafx.scene.paint.Color;
  import javafx.scene.shape.Rectangle;
  import javafx.scene.shape.RectangleBuilder;
  import javafx.scene.text.Font;
  import javafx.stage.Stage;
  
  public class SingleButton extends Application {
      Button btn;
      Scene scene;
      StackPane stack;
      Rectangle roundedRectangle;
  
      @Override
      public void start(Stage stage) throws Exception {
          btn = ButtonBuilder
                  .create()
                  .font(Font.font("DejaVu Sans Mono",22))
                  .text("Hello World")
                  .build();
  
          roundedRectangle = RectangleBuilder
                  .create()
                  .width(300)
                  .height(300)
                  .arcHeight(150)
                  .arcWidth(200)
                  .fill(Color.rgb(128, 128, 128))
                  .build();
  
          stack = StackPaneBuilder
                  .create()
                  .children(roundedRectangle , btn)
                  .build();
          stack.setMaxSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE);
  
          scene = SceneBuilder
                  .create()
                  .root(stack)
                  .build();
  
          stage.setScene(scene);
          stage.show();
  
  
      }
  
  
      public static void main(String[] args) {
          Application.launch("definitive_guide.SingleButton.java");
      }
  
  }  
  </code></pre>
  
  <p>For now, the values for the length , breadth and the arcs of the rectangle are manually entered. So, they are not dynamic.  </p>
  
  <p>I want to be able to set its size depending upon the size of the text plus some padding so as to have a consistent look and feel across devices of different resolutions.<br>
  In Swing, <code>FontMetrics</code> was handy but I do not know what to do in JavaFX.  </p>
  
  <p><strong>How do I do that?</strong></p>