Bartek Bartek - 1 month ago 27
Java Question

Binding drawing a rectangle with the data in the textField, JavaFx

How to correctly use the

widthProperty()
for data from
textField
?

widthRectangle.textProperty().bindBidirectional(rectangleObj.getWidthRectangleValue());
rectangle.widthProperty().bind(rectangleObj.getWidthRectangleValue());


The above does not work. Maybe I'll find somewhere how to use it properly?

Edit:

public class RectangleObj {


private StringProperty widthRectangleValue = new SimpleStringProperty();
private StringProperty heightRectangleValue = new SimpleStringProperty();

public StringProperty getWidthRectangleValue(){
return widthRectangleValue;
}

public void setWidthRectangleValue(StringProperty widthRectangleValue){
this.widthRectangleValue = widthRectangleValue;
}


public StringProperty getHeightRectangleValue(){
return heightRectangleValue;
}

public void setHeightRectangleValue(StringProperty heightRectangleValue){
this.heightRectangleValue = heightRectangleValue;
}
}


.

public class ControllerParametersForRectangle implements Initializable {


@FXML
Rectangle rectangle;

@FXML
TextField widthRectangle;

@FXML
TextField heightRectangle;

RectangleObj rectangleObj = new RectangleObj();

@Override
public void initialize(URL location, ResourceBundle resources) {

widthRectangle.textProperty().bindBidirectional(rectangleObj.getWidthRectangleValue());
rectangle.widthProperty().bind(rectangleObj.getWidthRectangleValue());


}
}

Answer

Do not bind the value to a StringProperty. Use a TextFromatter to convert the TextField's text to another type instead.

Example:

@Override
public void start(Stage primaryStage) {
    Rectangle rect = new Rectangle(100, 100);

    StringConverter<Double> converter = new DoubleStringConverter();

    TextField xTextField = new TextField();
    TextFormatter<Double> xFromatter = new TextFormatter<>(converter);
    xTextField.setTextFormatter(xFromatter);

    TextField widthTextField = new TextField();

    TextFormatter<Double> widthFromatter = new TextFormatter<Double>(converter);
    widthTextField.setTextFormatter(widthFromatter);

    xFromatter.valueProperty().bindBidirectional(rect.xProperty().asObject());
    widthFromatter.valueProperty().bindBidirectional(rect.widthProperty().asObject());

    Scene scene = new Scene(new VBox(10, xTextField, widthTextField, new Pane(rect)), 500, 500);

    primaryStage.setScene(scene);
    primaryStage.show();
}
Comments