0

I have a problem figuering out what the best procedure would be, to have a growing and shrinking BorderPane. I want to try and enlarge or shrink the Pane horizontally, based on a Text node child it has (with changing text length). There are some additional constraints / problems that I have to consider:

  • Can not use a Label, because they render worse in a 3D scene. Even with lcd / gray / Cache on or off.
  • The Text node does a linewrapping, if the text length is bigger than its bounding box width
  • Using setWrappingWidth(0) automatically right align's the Text node instead of the horizontal center alignment I need.
  • Using setWrappingWidht(Double.MAX_VALUE) throws exception in 3D scene when passing by with camera.
  • Have not figuered out how to actually set the width of the node. I can get it with getLayoutBounds().getWidth().
  • The Text Node class doesn't seem to have any usable width bindings?
Terran
  • 1,091
  • 18
  • 29

1 Answers1

0

After browsing around for a while I found this answer: Javafx textfield resize to text lenght? It contains a method for computing the width of text. I changed my BorderPane to contain a VBox, which in turn contains a TextField. However it should also work by setting the setWrappingWidth for the Text node. The TextUtils class I copied from above link.

public TextField getTop() {
    Node topNode = this.borderPane.getTop();
    if((topNode instanceof VBox)) {
        VBox topVBox = (VBox) topNode;
        if(!topVBox.getChildren().isEmpty() && topVBox.getChildren().get(0) instanceof TextField) {
            return (TextField) topVBox.getChildren().get(0);
        }
    }
    return null;
}

public void adaptWidthByText(Font font, String text) {
    // + 50px for some additional space to compensate insets, borders etc.
    double newWidth = TextUtils.computeTextWidth(font, text, 0.0D) + 50;
    this.borderPane.setPrefWidth(newWidth);
}

public void setTopText(String text) {
    TextField topTextField = getTop();
    if(topTextField == null) return;
    adaptWidthByText(topTextField.getFont(), text);
    topTextField.setText(text);
}
Community
  • 1
  • 1
Terran
  • 1,091
  • 18
  • 29