2016-11-29 51 views
0

我試圖創建具有自身內部的圖像部分文本框,類似於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,然後還加了ImageViewStackPane的孩子。該ImageView需要知道如何調整自己,所以我已綁定了fitHeightTextField的高度,在考慮TextField的的填充。

ImageViewfitWidth然後綁定到它自己的fitHeight

最後,我需要讓我的TextField的文本向右偏移(因爲圖像阻止它),所以我再次做了另一個綁定取決於ImageViewfitWidth

這與循環依賴,這導致堆棧溢出結束。有沒有其他的方法可以不用硬編碼TextField的左邊填充?

+0

爲什麼你需要調整圖像大小? –

回答

0

這裏是一個小爲例,我使用(StackPane/TextField/ImageView),但不是我的形象勸你與SVG繪製自己的形狀有它的完全控制(MouseHover /聚焦...),我以前也使用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; 
} 

希望這將幫助你!