使用textField,JavaFx中的数据绑定绘制矩形

时间:2016-10-06 18:31:40

标签: java javafx javafx-8

如何正确使用widthProperty()来自textField的数据?

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

以上不起作用。也许我会在某处找到如何正确使用它?

编辑:

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());


    }
}

1 个答案:

答案 0 :(得分:2)

不要将值绑定到StringProperty。使用TextFromatterTextField的文字转换为其他类型。

示例:

@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();
}