2017-01-10 60 views
1

我想要做的是:JavaFX的綁定標籤textProperty多個屬性的變化

我有一個JavaFX的窗口,我總是被拖動corners or the sides改變寬度和高度它。 I want when the width or height are changing那麼Label的文本有以下格式:

~Width=[here the width of the Window],Height[here the height of the Window]~ 

例子:

~Width=[1300],Height=[600]~ 

我想這樣做,使用綁定和不使用2(二)ChangeListeners

        I am trying: 

label.textProperty().bind(I am stack here on how to do this...); 

我也看過這個問題JavaFX bind to multiple properties

回答

4

只要使用Bindings.createStringBindingwidthheight作爲依賴:

StringBinding binding = Bindings.createStringBinding(
      () -> MessageFormat.format("~Width=[{0}],Height=[{1}]~", primaryStage.getWidth(), primaryStage.getHeight()), 
      primaryStage.widthProperty(), 
      primaryStage.heightProperty()); 

label.textProperty().bind(binding); 
+0

O_O很好,謝謝!第一次我看到'MessageFormat'類。 – GOXR3PLUS

1

我認爲最簡單的方法是使用一個變化監聽和查詢帶/高度值手動。像

public void init() 
{ 
    ChangeListener<Number> listener = (obs, ov, nv) -> update(); 
    node.widthProperty().addListener(listener); 
    node.heightProperty().addListener(listener); 
} 

public void update() 
{ 
     label.setText(String.format("width[%s] height[%s]", node.getWidth()), node.getHeight); 
}