【问题标题】:How to prevent circular binding dependency如何防止循环绑定依赖
【发布时间】:2017-04-13 06:25:18
【问题描述】:

我正在尝试创建一个内部包含图像部分的文本字段,类似于this

imageView.fitHeightProperty().bind(Bindings.createDoubleBinding(
    () -> textField.getHeight() -
          textField.getPadding().getTop() -
          textField.getPadding().getBottom(),
    textField.heightProperty(), textField.paddingProperty()));

imageView.fitWidthProperty().bind(imageView.fitHeightProperty());

textField.paddingProperty().bind(Bindings.createObjectBinding(
    () -> new Insets(textField.getPadding().getTop(),
                     textField.getPadding().getRight(),
                     textField.getPadding().getBottom(),
                     textField.getPadding().getRight() * 2 + imageView.getFitWidth()),
    imageView.fitWidthProperty(), textField.paddingProperty()));

我目前的方法是使用StackPane 来保存TextField,然后还添加一个ImageView 作为StackPane 的孩子。 ImageView 需要知道如何调整自身大小,因此我将其 fitHeight 绑定到 TextField 的高度,同时考虑到 TextField 的填充。

ImageViewfitWidth 然后绑定到它自己的fitHeight

最后,我需要让我的TextField 的文本向右偏移(因为图像挡住了它),所以我再次做了另一个依赖于ImageViewfitWidth 的绑定。

这会导致循环依赖,导致堆栈溢出。有没有其他方法可以在不对TextField 的左填充进行硬编码的情况下做到这一点?

【问题讨论】:

  • 为什么需要调整图片大小?

标签: java user-interface javafx data-binding javafx-8


【解决方案1】:

这里有一个小例子,我使用过 (StackPane/TextField/ImageView),但我建议您使用 SVG 绘制自己的形状以完全控制它(MouseHover/Focused...),而不是图像,我也使用了 CSS 来实现这一点:

Java:

    private StackPane sp = new StackPane();
    private TextField tf = new TextField();
    private ImageView iv;

    //Init StackPane
    sp.getStylesheets().add(getClass().getResource("style.css").toExternalForm()); 
    sp.getStyleClass().add("identifiant");
    sp.setPrefSize(200, 40);
    sp.setLayoutX(100);
    sp.setLayoutY(100);

    //Init ImageView
    iv = new ImageView(getClass().getResource("Img.png").toString());
    StackPane.setAlignment(iv, Pos.CENTER_LEFT);
    StackPane.setMargin(iv, new Insets(0, 0, 0, 10));

    //Init TextField
    StackPane.setAlignment(tf, Pos.CENTER_LEFT);
    StackPane.setMargin(tf, new Insets(2, 5, 0, 30));

    //Add all content
    sp.getChildren().addAll(iv,tf);

CSS:

.identifiant{

-fx-background-color:#45444a;
-fx-effect:innershadow(three-pass-box , rgba(0,0,0) , 6, 0.0 , 0 , 0); 
-fx-background-radius:8px;
 }

.text-field{

-fx-background-insets:0;
-fx-background-color:#45444a;
-fx-text-fill:white;
}

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    相关资源
    最近更新 更多